home *** CD-ROM | disk | FTP | other *** search
/ Australian Personal Computer 2002 November / CD 1 / APC0211D1.ISO / workshop / prog / files / ActivePerl-5.6.1.633-MSWin32.msi / _662c49f9627f56e1b904931a860d4acf < prev    next >
Encoding:
Text File  |  2001-09-04  |  85.9 KB  |  2,709 lines

  1. package DB;
  2.  
  3. # Debugger for Perl 5.00x; perl5db.pl patch level:
  4.  
  5. $VERSION = 1.07;
  6. $header = "perl5db.pl version $VERSION";
  7.  
  8. #
  9. # This file is automatically included if you do perl -d.
  10. # It's probably not useful to include this yourself.
  11. #
  12. # Perl supplies the values for %sub.  It effectively inserts
  13. # a &DB'DB(); in front of every place that can have a
  14. # breakpoint. Instead of a subroutine call it calls &DB::sub with
  15. # $DB::sub being the called subroutine. It also inserts a BEGIN
  16. # {require 'perl5db.pl'} before the first line.
  17. #
  18. # After each `require'd file is compiled, but before it is executed, a
  19. # call to DB::postponed($main::{'_<'.$filename}) is emulated. Here the
  20. # $filename is the expanded name of the `require'd file (as found as
  21. # value of %INC).
  22. #
  23. # Additional services from Perl interpreter:
  24. #
  25. # if caller() is called from the package DB, it provides some
  26. # additional data.
  27. #
  28. # The array @{$main::{'_<'.$filename}} is the line-by-line contents of
  29. # $filename.
  30. #
  31. # The hash %{'_<'.$filename} contains breakpoints and action (it is
  32. # keyed by line number), and individual entries are settable (as
  33. # opposed to the whole hash). Only true/false is important to the
  34. # interpreter, though the values used by perl5db.pl have the form
  35. # "$break_condition\0$action". Values are magical in numeric context.
  36. #
  37. # The scalar ${'_<'.$filename} contains $filename.
  38. #
  39. # Note that no subroutine call is possible until &DB::sub is defined
  40. # (for subroutines defined outside of the package DB). In fact the same is
  41. # true if $deep is not defined.
  42. #
  43. # $Log:    perldb.pl,v $
  44.  
  45. #
  46. # At start reads $rcfile that may set important options.  This file
  47. # may define a subroutine &afterinit that will be executed after the
  48. # debugger is initialized.
  49. #
  50. # After $rcfile is read reads environment variable PERLDB_OPTS and parses
  51. # it as a rest of `O ...' line in debugger prompt.
  52. #
  53. # The options that can be specified only at startup:
  54. # [To set in $rcfile, call &parse_options("optionName=new_value").]
  55. #
  56. # TTY  - the TTY to use for debugging i/o.
  57. #
  58. # noTTY - if set, goes in NonStop mode.  On interrupt if TTY is not set
  59. # uses the value of noTTY or "/tmp/perldbtty$$" to find TTY using
  60. # Term::Rendezvous.  Current variant is to have the name of TTY in this
  61. # file.
  62. #
  63. # ReadLine - If false, dummy ReadLine is used, so you can debug
  64. # ReadLine applications.
  65. #
  66. # NonStop - if true, no i/o is performed until interrupt.
  67. #
  68. # LineInfo - file or pipe to print line number info to.  If it is a
  69. # pipe, a short "emacs like" message is used.
  70. #
  71. # RemotePort - host:port to connect to on remote host for remote debugging.
  72. #
  73. # Example $rcfile: (delete leading hashes!)
  74. #
  75. # &parse_options("NonStop=1 LineInfo=db.out");
  76. # sub afterinit { $trace = 1; }
  77. #
  78. # The script will run without human intervention, putting trace
  79. # information into db.out.  (If you interrupt it, you would better
  80. # reset LineInfo to something "interactive"!)
  81. #
  82. ##################################################################
  83.  
  84. # Enhanced by ilya@math.ohio-state.edu (Ilya Zakharevich)
  85. # Latest version available: ftp://ftp.math.ohio-state.edu/pub/users/ilya/perl
  86.  
  87. # modified Perl debugger, to be run from Emacs in perldb-mode
  88. # Ray Lischner (uunet!mntgfx!lisch) as of 5 Nov 1990
  89. # Johan Vromans -- upgrade to 4.0 pl 10
  90. # Ilya Zakharevich -- patches after 5.001 (and some before ;-)
  91.  
  92. # Changelog:
  93.  
  94. # A lot of things changed after 0.94. First of all, core now informs
  95. # debugger about entry into XSUBs, overloaded operators, tied operations,
  96. # BEGIN and END. Handy with `O f=2'.
  97.  
  98. # This can make debugger a little bit too verbose, please be patient
  99. # and report your problems promptly.
  100.  
  101. # Now the option frame has 3 values: 0,1,2.
  102.  
  103. # Note that if DESTROY returns a reference to the object (or object),
  104. # the deletion of data may be postponed until the next function call,
  105. # due to the need to examine the return value.
  106.  
  107. # Changes: 0.95: `v' command shows versions.
  108. # Changes: 0.96: `v' command shows version of readline.
  109. #    primitive completion works (dynamic variables, subs for `b' and `l',
  110. #        options). Can `p %var'
  111. #    Better help (`h <' now works). New commands <<, >>, {, {{.
  112. #    {dump|print}_trace() coded (to be able to do it from <<cmd).
  113. #    `c sub' documented.
  114. #    At last enough magic combined to stop after the end of debuggee.
  115. #    !! should work now (thanks to Emacs bracket matching an extra
  116. #    `]' in a regexp is caught).
  117. #    `L', `D' and `A' span files now (as documented).
  118. #    Breakpoints in `require'd code are possible (used in `R').
  119. #    Some additional words on internal work of debugger.
  120. #    `b load filename' implemented.
  121. #    `b postpone subr' implemented.
  122. #    now only `q' exits debugger (overwriteable on $inhibit_exit).
  123. #    When restarting debugger breakpoints/actions persist.
  124. #     Buglet: When restarting debugger only one breakpoint/action per 
  125. #        autoloaded function persists.
  126. # Changes: 0.97: NonStop will not stop in at_exit().
  127. #    Option AutoTrace implemented.
  128. #    Trace printed differently if frames are printed too.
  129. #    new `inhibitExit' option.
  130. #    printing of a very long statement interruptible.
  131. # Changes: 0.98: New command `m' for printing possible methods
  132. #    'l -' is a synonim for `-'.
  133. #    Cosmetic bugs in printing stack trace.
  134. #    `frame' & 8 to print "expanded args" in stack trace.
  135. #    Can list/break in imported subs.
  136. #    new `maxTraceLen' option.
  137. #    frame & 4 and frame & 8 granted.
  138. #    new command `m'
  139. #    nonstoppable lines do not have `:' near the line number.
  140. #    `b compile subname' implemented.
  141. #    Will not use $` any more.
  142. #    `-' behaves sane now.
  143. # Changes: 0.99: Completion for `f', `m'.
  144. #    `m' will remove duplicate names instead of duplicate functions.
  145. #    `b load' strips trailing whitespace.
  146. #    completion ignores leading `|'; takes into account current package
  147. #    when completing a subroutine name (same for `l').
  148. # Changes: 1.07: Many fixed by tchrist 13-March-2000
  149. #   BUG FIXES:
  150. #   + Added bare mimimal security checks on perldb rc files, plus
  151. #     comments on what else is needed.
  152. #   + Fixed the ornaments that made "|h" completely unusable.
  153. #     They are not used in print_help if they will hurt.  Strip pod
  154. #     if we're paging to less.
  155. #   + Fixed mis-formatting of help messages caused by ornaments
  156. #     to restore Larry's original formatting.  
  157. #   + Fixed many other formatting errors.  The code is still suboptimal, 
  158. #     and needs a lot of work at restructuing. It's also misindented
  159. #     in many places.
  160. #   + Fixed bug where trying to look at an option like your pager
  161. #     shows "1".  
  162. #   + Fixed some $? processing.  Note: if you use csh or tcsh, you will
  163. #     lose.  You should consider shell escapes not using their shell,
  164. #     or else not caring about detailed status.  This should really be
  165. #     unified into one place, too.
  166. #   + Fixed bug where invisible trailing whitespace on commands hoses you,
  167. #     tricking Perl into thinking you wern't calling a debugger command!
  168. #   + Fixed bug where leading whitespace on commands hoses you.  (One
  169. #     suggests a leading semicolon or any other irrelevant non-whitespace
  170. #     to indicate literal Perl code.)
  171. #   + Fixed bugs that ate warnings due to wrong selected handle.
  172. #   + Fixed a precedence bug on signal stuff.
  173. #   + Fixed some unseemly wording.
  174. #   + Fixed bug in help command trying to call perl method code.
  175. #   + Fixed to call dumpvar from exception handler.  SIGPIPE killed us.
  176. #   ENHANCEMENTS:
  177. #   + Added some comments.  This code is still nasty spaghetti.
  178. #   + Added message if you clear your pre/post command stacks which was
  179. #     very easy to do if you just typed a bare >, <, or {.  (A command
  180. #     without an argument should *never* be a destructive action; this
  181. #     API is fundamentally screwed up; likewise option setting, which
  182. #     is equally buggered.)
  183. #   + Added command stack dump on argument of "?" for >, <, or {.
  184. #   + Added a semi-built-in doc viewer command that calls man with the
  185. #     proper %Config::Config path (and thus gets caching, man -k, etc),
  186. #     or else perldoc on obstreperous platforms.
  187. #   + Added to and rearranged the help information.
  188. #   + Detected apparent misuse of { ... } to declare a block; this used
  189. #     to work but now is a command, and mysteriously gave no complaint.
  190.  
  191. ####################################################################
  192.  
  193. # Needed for the statement after exec():
  194.  
  195. BEGIN { $ini_warn = $^W; $^W = 0 } # Switch compilation warnings off until another BEGIN.
  196. local($^W) = 0;            # Switch run-time warnings off during init.
  197. warn (            # Do not ;-)
  198.       $dumpvar::hashDepth,     
  199.       $dumpvar::arrayDepth,    
  200.       $dumpvar::dumpDBFiles,   
  201.       $dumpvar::dumpPackages,  
  202.       $dumpvar::quoteHighBit,  
  203.       $dumpvar::printUndef,    
  204.       $dumpvar::globPrint,     
  205.       $dumpvar::usageOnly,
  206.       @ARGS,
  207.       $Carp::CarpLevel,
  208.       $panic,
  209.       $second_time,
  210.      ) if 0;
  211.  
  212. # Command-line + PERLLIB:
  213. @ini_INC = @INC;
  214.  
  215. # $prevwarn = $prevdie = $prevbus = $prevsegv = ''; # Does not help?!
  216.  
  217. $trace = $signal = $single = 0;    # Uninitialized warning suppression
  218.                                 # (local $^W cannot help - other packages!).
  219. $inhibit_exit = $option{PrintRet} = 1;
  220.  
  221. @options     = qw(hashDepth arrayDepth DumpDBFiles DumpPackages DumpReused
  222.           compactDump veryCompact quote HighBit undefPrint
  223.           globPrint PrintRet UsageOnly frame AutoTrace
  224.           TTY noTTY ReadLine NonStop LineInfo maxTraceLen
  225.           recallCommand ShellBang pager tkRunning ornaments
  226.           signalLevel warnLevel dieLevel inhibit_exit
  227.           ImmediateStop bareStringify
  228.           RemotePort);
  229.  
  230. %optionVars    = (
  231.          hashDepth    => \$dumpvar::hashDepth,
  232.          arrayDepth    => \$dumpvar::arrayDepth,
  233.          DumpDBFiles    => \$dumpvar::dumpDBFiles,
  234.          DumpPackages    => \$dumpvar::dumpPackages,
  235.          DumpReused    => \$dumpvar::dumpReused,
  236.          HighBit    => \$dumpvar::quoteHighBit,
  237.          undefPrint    => \$dumpvar::printUndef,
  238.          globPrint    => \$dumpvar::globPrint,
  239.          UsageOnly    => \$dumpvar::usageOnly,     
  240.          bareStringify    => \$dumpvar::bareStringify,
  241.          frame          => \$frame,
  242.          AutoTrace      => \$trace,
  243.          inhibit_exit   => \$inhibit_exit,
  244.          maxTraceLen    => \$maxtrace,
  245.          ImmediateStop    => \$ImmediateStop,
  246.          RemotePort    => \$remoteport,
  247. );
  248.  
  249. %optionAction  = (
  250.           compactDump    => \&dumpvar::compactDump,
  251.           veryCompact    => \&dumpvar::veryCompact,
  252.           quote        => \&dumpvar::quote,
  253.           TTY        => \&TTY,
  254.           noTTY        => \&noTTY,
  255.           ReadLine    => \&ReadLine,
  256.           NonStop    => \&NonStop,
  257.           LineInfo    => \&LineInfo,
  258.           recallCommand    => \&recallCommand,
  259.           ShellBang    => \&shellBang,
  260.           pager        => \&pager,
  261.           signalLevel    => \&signalLevel,
  262.           warnLevel    => \&warnLevel,
  263.           dieLevel    => \&dieLevel,
  264.           tkRunning    => \&tkRunning,
  265.           ornaments    => \&ornaments,
  266.           RemotePort    => \&RemotePort,
  267.          );
  268.  
  269. %optionRequire = (
  270.           compactDump    => 'dumpvar.pl',
  271.           veryCompact    => 'dumpvar.pl',
  272.           quote        => 'dumpvar.pl',
  273.          );
  274.  
  275. # These guys may be defined in $ENV{PERL5DB} :
  276. $rl        = 1    unless defined $rl;
  277. $warnLevel    = 0    unless defined $warnLevel;
  278. $dieLevel    = 0    unless defined $dieLevel;
  279. $signalLevel    = 1    unless defined $signalLevel;
  280. $pre        = []    unless defined $pre;
  281. $post        = []    unless defined $post;
  282. $pretype    = []    unless defined $pretype;
  283.  
  284. warnLevel($warnLevel);
  285. dieLevel($dieLevel);
  286. signalLevel($signalLevel);
  287.  
  288. &pager(
  289.     (defined($ENV{PAGER}) 
  290.     ? $ENV{PAGER}
  291.     : ($^O eq 'os2' 
  292.        ? 'cmd /c more' 
  293.        : 'more'))) unless defined $pager;
  294. setman();
  295. &recallCommand("!") unless defined $prc;
  296. &shellBang("!") unless defined $psh;
  297. $maxtrace = 400 unless defined $maxtrace;
  298.  
  299. if (-e "/dev/tty") {  # this is the wrong metric!
  300.   $rcfile=".perldb";
  301. } else {
  302.   $rcfile="perldb.ini";
  303. }
  304.  
  305. # This isn't really safe, because there's a race
  306. # between checking and opening.  The solution is to
  307. # open and fstat the handle, but then you have to read and
  308. # eval the contents.  But then the silly thing gets
  309. # your lexical scope, which is unfortunately at best.
  310. sub safe_do { 
  311.     my $file = shift;
  312.  
  313.     # Just exactly what part of the word "CORE::" don't you understand?
  314.     local $SIG{__WARN__};  
  315.     local $SIG{__DIE__};    
  316.  
  317.     unless (is_safe_file($file)) {
  318.     CORE::warn <<EO_GRIPE;
  319. perldb: Must not source insecure rcfile $file.
  320.         You or the superuser must be the owner, and it must not 
  321.     be writable by anyone but its owner.
  322. EO_GRIPE
  323.     return;
  324.     } 
  325.  
  326.     do $file;
  327.     CORE::warn("perldb: couldn't parse $file: $@") if $@;
  328. }
  329.  
  330.  
  331. # Verifies that owner is either real user or superuser and that no
  332. # one but owner may write to it.  This function is of limited use
  333. # when called on a path instead of upon a handle, because there are
  334. # no guarantees that filename (by dirent) whose file (by ino) is
  335. # eventually accessed is the same as the one tested. 
  336. # Assumes that the file's existence is not in doubt.
  337. sub is_safe_file {
  338.     my $path = shift;
  339.     stat($path) || return;    # mysteriously vaporized
  340.     my($dev,$ino,$mode,$nlink,$uid,$gid) = stat(_);
  341.  
  342.     return 0 if $uid != 0 && $uid != $<;
  343.     return 0 if $mode & 022;
  344.     return 1;
  345. }
  346.  
  347. if (-f $rcfile) {
  348.     safe_do("./$rcfile");
  349. elsif (defined $ENV{HOME} && -f "$ENV{HOME}/$rcfile") {
  350.     safe_do("$ENV{HOME}/$rcfile");
  351. }
  352. elsif (defined $ENV{LOGDIR} && -f "$ENV{LOGDIR}/$rcfile") {
  353.     safe_do("$ENV{LOGDIR}/$rcfile");
  354. }
  355.  
  356. if (defined $ENV{PERLDB_OPTS}) {
  357.   parse_options($ENV{PERLDB_OPTS});
  358. }
  359.  
  360. # Here begin the unreadable code.  It needs fixing.
  361.  
  362. if (exists $ENV{PERLDB_RESTART}) {
  363.   delete $ENV{PERLDB_RESTART};
  364.   # $restart = 1;
  365.   @hist = get_list('PERLDB_HIST');
  366.   %break_on_load = get_list("PERLDB_ON_LOAD");
  367.   %postponed = get_list("PERLDB_POSTPONE");
  368.   my @had_breakpoints= get_list("PERLDB_VISITED");
  369.   for (0 .. $#had_breakpoints) {
  370.     my %pf = get_list("PERLDB_FILE_$_");
  371.     $postponed_file{$had_breakpoints[$_]} = \%pf if %pf;
  372.   }
  373.   my %opt = get_list("PERLDB_OPT");
  374.   my ($opt,$val);
  375.   while (($opt,$val) = each %opt) {
  376.     $val =~ s/[\\\']/\\$1/g;
  377.     parse_options("$opt'$val'");
  378.   }
  379.   @INC = get_list("PERLDB_INC");
  380.   @ini_INC = @INC;
  381.   $pretype = [get_list("PERLDB_PRETYPE")];
  382.   $pre = [get_list("PERLDB_PRE")];
  383.   $post = [get_list("PERLDB_POST")];
  384.   @typeahead = get_list("PERLDB_TYPEAHEAD", @typeahead);
  385. }
  386.  
  387. if ($notty) {
  388.   $runnonstop = 1;
  389. } else {
  390.   # Is Perl being run from a slave editor or graphical debugger?
  391.   $slave_editor = ((defined $main::ARGV[0]) and ($main::ARGV[0] eq '-emacs'));
  392.   $rl = 0, shift(@main::ARGV) if $slave_editor;
  393.  
  394.   #require Term::ReadLine;
  395.  
  396.   if ($^O eq 'cygwin') {
  397.     # /dev/tty is binary. use stdin for textmode
  398.     undef $console;
  399.   } elsif (-e "/dev/tty") {
  400.     $console = "/dev/tty";
  401.   } elsif ($^O eq 'dos' or -e "con" or $^O eq 'MSWin32') {
  402.     $console = "con";
  403.   } elsif ($^O eq 'MacOS') {
  404.     if ($MacPerl::Version !~ /MPW/) {
  405.       $console = "Dev:Console:Perl Debug"; # Separate window for application
  406.     } else {
  407.       $console = "Dev:Console";
  408.     }
  409.   } else {
  410.     $console = "sys\$command";
  411.   }
  412.  
  413.   if (($^O eq 'MSWin32') and ($slave_editor or defined $ENV{EMACS})) {
  414.     $console = undef;
  415.   }
  416.  
  417.   # Around a bug:
  418.   if (defined $ENV{OS2_SHELL} and ($slave_editor or $ENV{WINDOWID})) { # In OS/2
  419.     $console = undef;
  420.   }
  421.  
  422.   if ($^O eq 'epoc') {
  423.     $console = undef;
  424.   }
  425.  
  426.   $console = $tty if defined $tty;
  427.  
  428.   if (defined $remoteport) {
  429.     require IO::Socket;
  430.     $OUT = new IO::Socket::INET( Timeout  => '10',
  431.                                  PeerAddr => $remoteport,
  432.                                  Proto    => 'tcp',
  433.                                );
  434.     if (!$OUT) { die "Unable to connect to remote host: $remoteport\n"; }
  435.     $IN = $OUT;
  436.   }
  437.   else {
  438.     if (defined $console) {
  439.       open(IN,"+<$console") || open(IN,"<$console") || open(IN,"<&STDIN");
  440.       open(OUT,"+>$console") || open(OUT,">$console") || open(OUT,">&STDERR")
  441.         || open(OUT,">&STDOUT");    # so we don't dongle stdout
  442.     } else {
  443.       open(IN,"<&STDIN");
  444.       open(OUT,">&STDERR") || open(OUT,">&STDOUT"); # so we don't dongle stdout
  445.       $console = 'STDIN/OUT';
  446.     }
  447.     # so open("|more") can read from STDOUT and so we don't dingle stdin
  448.     $IN = \*IN;
  449.  
  450.     $OUT = \*OUT;
  451.   }
  452.   select($OUT);
  453.   $| = 1;            # for DB::OUT
  454.   select(STDOUT);
  455.  
  456.   $LINEINFO = $OUT unless defined $LINEINFO;
  457.   $lineinfo = $console unless defined $lineinfo;
  458.  
  459.   $| = 1;            # for real STDOUT
  460.  
  461.   $header =~ s/.Header: ([^,]+),v(\s+\S+\s+\S+).*$/$1$2/;
  462.   unless ($runnonstop) {
  463.     print $OUT "\nLoading DB routines from $header\n";
  464.     print $OUT ("Editor support ",
  465.         $slave_editor ? "enabled" : "available",
  466.         ".\n");
  467.     print $OUT "\nEnter h or `h h' for help, or `$doccmd perldebug' for more help.\n\n";
  468.   }
  469. }
  470.  
  471. @ARGS = @ARGV;
  472. for (@args) {
  473.     s/\'/\\\'/g;
  474.     s/(.*)/'$1'/ unless /^-?[\d.]+$/;
  475. }
  476.  
  477. if (defined &afterinit) {    # May be defined in $rcfile
  478.   &afterinit();
  479. }
  480.  
  481. $I_m_init = 1;
  482.  
  483. ############################################################ Subroutines
  484.  
  485. sub DB {
  486.     # _After_ the perl program is compiled, $single is set to 1:
  487.     if ($single and not $second_time++) {
  488.       if ($runnonstop) {    # Disable until signal
  489.     for ($i=0; $i <= $stack_depth; ) {
  490.         $stack[$i++] &= ~1;
  491.     }
  492.     $single = 0;
  493.     # return;            # Would not print trace!
  494.       } elsif ($ImmediateStop) {
  495.     $ImmediateStop = 0;
  496.     $signal = 1;
  497.       }
  498.     }
  499.     $runnonstop = 0 if $single or $signal; # Disable it if interactive.
  500.     &save;
  501.     ($package, $filename, $line) = caller;
  502.     $filename_ini = $filename;
  503.     $usercontext = '($@, $!, $^E, $,, $/, $\, $^W) = @saved;' .
  504.       "package $package;";    # this won't let them modify, alas
  505.     local(*dbline) = $main::{'_<' . $filename};
  506.     $max = $#dbline;
  507.     if (($stop,$action) = split(/\0/,$dbline{$line})) {
  508.     if ($stop eq '1') {
  509.         $signal |= 1;
  510.     } elsif ($stop) {
  511.         $evalarg = "\$DB::signal |= 1 if do {$stop}"; &eval;
  512.         $dbline{$line} =~ s/;9($|\0)/$1/;
  513.     }
  514.     }
  515.     my $was_signal = $signal;
  516.     if ($trace & 2) {
  517.       for (my $n = 0; $n <= $#to_watch; $n++) {
  518.     $evalarg = $to_watch[$n];
  519.     local $onetimeDump;    # Do not output results
  520.     my ($val) = &eval;    # Fix context (&eval is doing array)?
  521.     $val = ( (defined $val) ? "'$val'" : 'undef' );
  522.     if ($val ne $old_watch[$n]) {
  523.       $signal = 1;
  524.       print $OUT <<EOP;
  525. Watchpoint $n:\t$to_watch[$n] changed:
  526.     old value:\t$old_watch[$n]
  527.     new value:\t$val
  528. EOP
  529.       $old_watch[$n] = $val;
  530.     }
  531.       }
  532.     }
  533.     if ($trace & 4) {        # User-installed watch
  534.       return if watchfunction($package, $filename, $line) 
  535.     and not $single and not $was_signal and not ($trace & ~4);
  536.     }
  537.     $was_signal = $signal;
  538.     $signal = 0;
  539.     if ($single || ($trace & 1) || $was_signal) {
  540.     if ($slave_editor) {
  541.         $position = "\032\032$filename:$line:0\n";
  542.         print $LINEINFO $position;
  543.     } elsif ($package eq 'DB::fake') {
  544.       $term || &setterm;
  545.       print_help(<<EOP);
  546. Debugged program terminated.  Use B<q> to quit or B<R> to restart,
  547.   use B<O> I<inhibit_exit> to avoid stopping after program termination,
  548.   B<h q>, B<h R> or B<h O> to get additional info.  
  549. EOP
  550.       $package = 'main';
  551.       $usercontext = '($@, $!, $^E, $,, $/, $\, $^W) = @saved;' .
  552.         "package $package;";    # this won't let them modify, alas
  553.     } else {
  554.         $sub =~ s/\'/::/;
  555.         $prefix = $sub =~ /::/ ? "" : "${'package'}::";
  556.         $prefix .= "$sub($filename:";
  557.         $after = ($dbline[$line] =~ /\n$/ ? '' : "\n");
  558.         if (length($prefix) > 30) {
  559.             $position = "$prefix$line):\n$line:\t$dbline[$line]$after";
  560.         $prefix = "";
  561.         $infix = ":\t";
  562.         } else {
  563.         $infix = "):\t";
  564.         $position = "$prefix$line$infix$dbline[$line]$after";
  565.         }
  566.         if ($frame) {
  567.         print $LINEINFO ' ' x $stack_depth, "$line:\t$dbline[$line]$after";
  568.         } else {
  569.         print $LINEINFO $position;
  570.         }
  571.         for ($i = $line + 1; $i <= $max && $dbline[$i] == 0; ++$i) { #{ vi
  572.         last if $dbline[$i] =~ /^\s*[\;\}\#\n]/;
  573.         last if $signal;
  574.         $after = ($dbline[$i] =~ /\n$/ ? '' : "\n");
  575.         $incr_pos = "$prefix$i$infix$dbline[$i]$after";
  576.         $position .= $incr_pos;
  577.         if ($frame) {
  578.             print $LINEINFO ' ' x $stack_depth, "$i:\t$dbline[$i]$after";
  579.         } else {
  580.             print $LINEINFO $incr_pos;
  581.         }
  582.         }
  583.     }
  584.     }
  585.     $evalarg = $action, &eval if $action;
  586.     if ($single || $was_signal) {
  587.     local $level = $level + 1;
  588.     foreach $evalarg (@$pre) {
  589.       &eval;
  590.     }
  591.     print $OUT $stack_depth . " levels deep in subroutine calls!\n"
  592.       if $single & 4;
  593.     $start = $line;
  594.     $incr = -1;        # for backward motion.
  595.     @typeahead = (@$pretype, @typeahead);
  596.       CMD:
  597.     while (($term || &setterm),
  598.            ($term_pid == $$ or &resetterm),
  599.            defined ($cmd=&readline("  DB" . ('<' x $level) .
  600.                        ($#hist+1) . ('>' x $level) .
  601.                        " "))) 
  602.         {
  603.         $single = 0;
  604.         $signal = 0;
  605.         $cmd =~ s/\\$/\n/ && do {
  606.             $cmd .= &readline("  cont: ");
  607.             redo CMD;
  608.         };
  609.         $cmd =~ /^$/ && ($cmd = $laststep);
  610.         push(@hist,$cmd) if length($cmd) > 1;
  611.           PIPE: {
  612.             $cmd =~ s/^\s+//s;   # trim annoying leading whitespace
  613.             $cmd =~ s/\s+$//s;   # trim annoying trailing whitespace
  614.             ($i) = split(/\s+/,$cmd);
  615.             if ($alias{$i}) { 
  616.             # squelch the sigmangler
  617.             local $SIG{__DIE__};
  618.             local $SIG{__WARN__};
  619.             eval "\$cmd =~ $alias{$i}";
  620.             if ($@) {
  621.                 print $OUT "Couldn't evaluate `$i' alias: $@";
  622.                 next CMD;
  623.             } 
  624.             }
  625.                    $cmd =~ /^q$/ && ($fall_off_end = 1) && exit $?;
  626.             $cmd =~ /^h$/ && do {
  627.             print_help($help);
  628.             next CMD; };
  629.             $cmd =~ /^h\s+h$/ && do {
  630.             print_help($summary);
  631.             next CMD; };
  632.             # support long commands; otherwise bogus errors
  633.             # happen when you ask for h on <CR> for example
  634.             $cmd =~ /^h\s+(\S.*)$/ && do {      
  635.             my $asked = $1;            # for proper errmsg
  636.             my $qasked = quotemeta($asked); # for searching
  637.             # XXX: finds CR but not <CR>
  638.             if ($help =~ /^<?(?:[IB]<)$qasked/m) {
  639.               while ($help =~ /^(<?(?:[IB]<)$qasked([\s\S]*?)\n)(?!\s)/mg) {
  640.                 print_help($1);
  641.               }
  642.             } else {
  643.                 print_help("B<$asked> is not a debugger command.\n");
  644.             }
  645.             next CMD; };
  646.             $cmd =~ /^t$/ && do {
  647.             $trace ^= 1;
  648.             print $OUT "Trace = " .
  649.                 (($trace & 1) ? "on" : "off" ) . "\n";
  650.             next CMD; };
  651.             $cmd =~ /^S(\s+(!)?(.+))?$/ && do {
  652.             $Srev = defined $2; $Spatt = $3; $Snocheck = ! defined $1;
  653.             foreach $subname (sort(keys %sub)) {
  654.                 if ($Snocheck or $Srev^($subname =~ /$Spatt/)) {
  655.                 print $OUT $subname,"\n";
  656.                 }
  657.             }
  658.             next CMD; };
  659.             $cmd =~ /^v$/ && do {
  660.             list_versions(); next CMD};
  661.             $cmd =~ s/^X\b/V $package/;
  662.             $cmd =~ /^V$/ && do {
  663.             $cmd = "V $package"; };
  664.             $cmd =~ /^V\b\s*(\S+)\s*(.*)/ && do {
  665.             local ($savout) = select($OUT);
  666.             $packname = $1;
  667.             @vars = split(' ',$2);
  668.             do 'dumpvar.pl' unless defined &main::dumpvar;
  669.             if (defined &main::dumpvar) {
  670.                 local $frame = 0;
  671.                 local $doret = -2;
  672.                 # must detect sigpipe failures
  673.                 eval { &main::dumpvar($packname,@vars) };
  674.                 if ($@) {
  675.                 die unless $@ =~ /dumpvar print failed/;
  676.                 } 
  677.             } else {
  678.                 print $OUT "dumpvar.pl not available.\n";
  679.             }
  680.             select ($savout);
  681.             next CMD; };
  682.             $cmd =~ s/^x\b/ / && do { # So that will be evaled
  683.             $onetimeDump = 'dump'; };
  684.             $cmd =~ s/^m\s+([\w:]+)\s*$/ / && do {
  685.             methods($1); next CMD};
  686.             $cmd =~ s/^m\b/ / && do { # So this will be evaled
  687.             $onetimeDump = 'methods'; };
  688.             $cmd =~ /^f\b\s*(.*)/ && do {
  689.             $file = $1;
  690.             $file =~ s/\s+$//;
  691.             if (!$file) {
  692.                 print $OUT "The old f command is now the r command.\n";
  693.                 print $OUT "The new f command switches filenames.\n";
  694.                 next CMD;
  695.             }
  696.             if (!defined $main::{'_<' . $file}) {
  697.                 if (($try) = grep(m#^_<.*$file#, keys %main::)) {{
  698.                           $try = substr($try,2);
  699.                           print $OUT "Choosing $try matching `$file':\n";
  700.                           $file = $try;
  701.                       }}
  702.             }
  703.             if (!defined $main::{'_<' . $file}) {
  704.                 print $OUT "No file matching `$file' is loaded.\n";
  705.                 next CMD;
  706.             } elsif ($file ne $filename) {
  707.                 *dbline = $main::{'_<' . $file};
  708.                 $max = $#dbline;
  709.                 $filename = $file;
  710.                 $start = 1;
  711.                 $cmd = "l";
  712.               } else {
  713.                 print $OUT "Already in $file.\n";
  714.                 next CMD;
  715.               }
  716.               };
  717.             $cmd =~ s/^l\s+-\s*$/-/;
  718.             $cmd =~ /^([lb])\b\s*(\$.*)/s && do {
  719.             $evalarg = $2;
  720.             my ($s) = &eval;
  721.             print($OUT "Error: $@\n"), next CMD if $@;
  722.             $s = CvGV_name($s);
  723.             print($OUT "Interpreted as: $1 $s\n");
  724.             $cmd = "$1 $s";
  725.             };
  726.             $cmd =~ /^l\b\s*([\':A-Za-z_][\':\w]*(\[.*\])?)/s && do {
  727.             $subname = $1;
  728.             $subname =~ s/\'/::/;
  729.             $subname = $package."::".$subname 
  730.               unless $subname =~ /::/;
  731.             $subname = "main".$subname if substr($subname,0,2) eq "::";
  732.             @pieces = split(/:/,find_sub($subname) || $sub{$subname});
  733.             $subrange = pop @pieces;
  734.             $file = join(':', @pieces);
  735.             if ($file ne $filename) {
  736.                 print $OUT "Switching to file '$file'.\n"
  737.                 unless $slave_editor;
  738.                 *dbline = $main::{'_<' . $file};
  739.                 $max = $#dbline;
  740.                 $filename = $file;
  741.             }
  742.             if ($subrange) {
  743.                 if (eval($subrange) < -$window) {
  744.                 $subrange =~ s/-.*/+/;
  745.                 }
  746.                 $cmd = "l $subrange";
  747.             } else {
  748.                 print $OUT "Subroutine $subname not found.\n";
  749.                 next CMD;
  750.             } };
  751.             $cmd =~ /^\.$/ && do {
  752.             $incr = -1;        # for backward motion.
  753.             $start = $line;
  754.             $filename = $filename_ini;
  755.             *dbline = $main::{'_<' . $filename};
  756.             $max = $#dbline;
  757.             print $LINEINFO $position;
  758.             next CMD };
  759.             $cmd =~ /^w\b\s*(\d*)$/ && do {
  760.             $incr = $window - 1;
  761.             $start = $1 if $1;
  762.             $start -= $preview;
  763.             #print $OUT 'l ' . $start . '-' . ($start + $incr);
  764.             $cmd = 'l ' . $start . '-' . ($start + $incr); };
  765.             $cmd =~ /^-$/ && do {
  766.             $start -= $incr + $window + 1;
  767.             $start = 1 if $start <= 0;
  768.             $incr = $window - 1;
  769.             $cmd = 'l ' . ($start) . '+'; };
  770.             $cmd =~ /^l$/ && do {
  771.             $incr = $window - 1;
  772.             $cmd = 'l ' . $start . '-' . ($start + $incr); };
  773.             $cmd =~ /^l\b\s*(\d*)\+(\d*)$/ && do {
  774.             $start = $1 if $1;
  775.             $incr = $2;
  776.             $incr = $window - 1 unless $incr;
  777.             $cmd = 'l ' . $start . '-' . ($start + $incr); };
  778.             $cmd =~ /^l\b\s*((-?[\d\$\.]+)([-,]([\d\$\.]+))?)?/ && do {
  779.             $end = (!defined $2) ? $max : ($4 ? $4 : $2);
  780.             $end = $max if $end > $max;
  781.             $i = $2;
  782.             $i = $line if $i eq '.';
  783.             $i = 1 if $i < 1;
  784.             $incr = $end - $i;
  785.             if ($slave_editor) {
  786.                 print $OUT "\032\032$filename:$i:0\n";
  787.                 $i = $end;
  788.             } else {
  789.                 for (; $i <= $end; $i++) {
  790.                     ($stop,$action) = split(/\0/, $dbline{$i});
  791.                     $arrow = ($i==$line 
  792.                       and $filename eq $filename_ini) 
  793.                   ?  '==>' 
  794.                     : ($dbline[$i]+0 ? ':' : ' ') ;
  795.                 $arrow .= 'b' if $stop;
  796.                 $arrow .= 'a' if $action;
  797.                 print $OUT "$i$arrow\t", $dbline[$i];
  798.                 $i++, last if $signal;
  799.                 }
  800.                 print $OUT "\n" unless $dbline[$i-1] =~ /\n$/;
  801.             }
  802.             $start = $i; # remember in case they want more
  803.             $start = $max if $start > $max;
  804.             next CMD; };
  805.             $cmd =~ /^D$/ && do {
  806.               print $OUT "Deleting all breakpoints...\n";
  807.               my $file;
  808.               for $file (keys %had_breakpoints) {
  809.             local *dbline = $main::{'_<' . $file};
  810.             my $max = $#dbline;
  811.             my $was;
  812.             
  813.             for ($i = 1; $i <= $max ; $i++) {
  814.                 if (defined $dbline{$i}) {
  815.                 $dbline{$i} =~ s/^[^\0]+//;
  816.                 if ($dbline{$i} =~ s/^\0?$//) {
  817.                     delete $dbline{$i};
  818.                 }
  819.                 }
  820.             }
  821.             
  822.             if (not $had_breakpoints{$file} &= ~1) {
  823.                 delete $had_breakpoints{$file};
  824.             }
  825.               }
  826.               undef %postponed;
  827.               undef %postponed_file;
  828.               undef %break_on_load;
  829.               next CMD; };
  830.             $cmd =~ /^L$/ && do {
  831.               my $file;
  832.               for $file (keys %had_breakpoints) {
  833.             local *dbline = $main::{'_<' . $file};
  834.             my $max = $#dbline;
  835.             my $was;
  836.             
  837.             for ($i = 1; $i <= $max; $i++) {
  838.                 if (defined $dbline{$i}) {
  839.                     print $OUT "$file:\n" unless $was++;
  840.                 print $OUT " $i:\t", $dbline[$i];
  841.                 ($stop,$action) = split(/\0/, $dbline{$i});
  842.                 print $OUT "   break if (", $stop, ")\n"
  843.                   if $stop;
  844.                 print $OUT "   action:  ", $action, "\n"
  845.                   if $action;
  846.                 last if $signal;
  847.                 }
  848.             }
  849.               }
  850.               if (%postponed) {
  851.             print $OUT "Postponed breakpoints in subroutines:\n";
  852.             my $subname;
  853.             for $subname (keys %postponed) {
  854.               print $OUT " $subname\t$postponed{$subname}\n";
  855.               last if $signal;
  856.             }
  857.               }
  858.               my @have = map { # Combined keys
  859.             keys %{$postponed_file{$_}}
  860.               } keys %postponed_file;
  861.               if (@have) {
  862.             print $OUT "Postponed breakpoints in files:\n";
  863.             my ($file, $line);
  864.             for $file (keys %postponed_file) {
  865.               my $db = $postponed_file{$file};
  866.               print $OUT " $file:\n";
  867.               for $line (sort {$a <=> $b} keys %$db) {
  868.                 print $OUT "  $line:\n";
  869.                 my ($stop,$action) = split(/\0/, $$db{$line});
  870.                 print $OUT "    break if (", $stop, ")\n"
  871.                   if $stop;
  872.                 print $OUT "    action:  ", $action, "\n"
  873.                   if $action;
  874.                 last if $signal;
  875.               }
  876.               last if $signal;
  877.             }
  878.               }
  879.               if (%break_on_load) {
  880.             print $OUT "Breakpoints on load:\n";
  881.             my $file;
  882.             for $file (keys %break_on_load) {
  883.               print $OUT " $file\n";
  884.               last if $signal;
  885.             }
  886.               }
  887.               if ($trace & 2) {
  888.             print $OUT "Watch-expressions:\n";
  889.             my $expr;
  890.             for $expr (@to_watch) {
  891.               print $OUT " $expr\n";
  892.               last if $signal;
  893.             }
  894.               }
  895.               next CMD; };
  896.             $cmd =~ /^b\b\s*load\b\s*(.*)/ && do {
  897.             my $file = $1; $file =~ s/\s+$//;
  898.             {
  899.               $break_on_load{$file} = 1;
  900.               $break_on_load{$::INC{$file}} = 1 if $::INC{$file};
  901.               $file .= '.pm', redo unless $file =~ /\./;
  902.             }
  903.             $had_breakpoints{$file} |= 1;
  904.             print $OUT "Will stop on load of `@{[join '\', `', sort keys %break_on_load]}'.\n";
  905.             next CMD; };
  906.             $cmd =~ /^b\b\s*(postpone|compile)\b\s*([':A-Za-z_][':\w]*)\s*(.*)/ && do {
  907.             my $cond = length $3 ? $3 : '1';
  908.             my ($subname, $break) = ($2, $1 eq 'postpone');
  909.             $subname =~ s/\'/::/g;
  910.             $subname = "${'package'}::" . $subname
  911.               unless $subname =~ /::/;
  912.             $subname = "main".$subname if substr($subname,0,2) eq "::";
  913.             $postponed{$subname} = $break 
  914.               ? "break +0 if $cond" : "compile";
  915.             next CMD; };
  916.             $cmd =~ /^b\b\s*([':A-Za-z_][':\w]*(?:\[.*\])?)\s*(.*)/ && do {
  917.             $subname = $1;
  918.             $cond = length $2 ? $2 : '1';
  919.             $subname =~ s/\'/::/g;
  920.             $subname = "${'package'}::" . $subname
  921.               unless $subname =~ /::/;
  922.             $subname = "main".$subname if substr($subname,0,2) eq "::";
  923.             # Filename below can contain ':'
  924.             ($file,$i) = (find_sub($subname) =~ /^(.*):(.*)$/);
  925.             $i += 0;
  926.             if ($i) {
  927.                 local $filename = $file;
  928.                 local *dbline = $main::{'_<' . $filename};
  929.                 $had_breakpoints{$filename} |= 1;
  930.                 $max = $#dbline;
  931.                 ++$i while $dbline[$i] == 0 && $i < $max;
  932.                 $dbline{$i} =~ s/^[^\0]*/$cond/;
  933.             } else {
  934.                 print $OUT "Subroutine $subname not found.\n";
  935.             }
  936.             next CMD; };
  937.             $cmd =~ /^b\b\s*(\d*)\s*(.*)/ && do {
  938.             $i = $1 || $line;
  939.             $cond = length $2 ? $2 : '1';
  940.             if ($dbline[$i] == 0) {
  941.                 print $OUT "Line $i not breakable.\n";
  942.             } else {
  943.                 $had_breakpoints{$filename} |= 1;
  944.                 $dbline{$i} =~ s/^[^\0]*/$cond/;
  945.             }
  946.             next CMD; };
  947.             $cmd =~ /^d\b\s*(\d*)/ && do {
  948.             $i = $1 || $line;
  949.                         if ($dbline[$i] == 0) {
  950.                             print $OUT "Line $i not breakable.\n";
  951.                         } else {
  952.                 $dbline{$i} =~ s/^[^\0]*//;
  953.                 delete $dbline{$i} if $dbline{$i} eq '';
  954.                         }
  955.             next CMD; };
  956.             $cmd =~ /^A$/ && do {
  957.               print $OUT "Deleting all actions...\n";
  958.               my $file;
  959.               for $file (keys %had_breakpoints) {
  960.             local *dbline = $main::{'_<' . $file};
  961.             my $max = $#dbline;
  962.             my $was;
  963.             
  964.             for ($i = 1; $i <= $max ; $i++) {
  965.                 if (defined $dbline{$i}) {
  966.                 $dbline{$i} =~ s/\0[^\0]*//;
  967.                 delete $dbline{$i} if $dbline{$i} eq '';
  968.                 }
  969.             }
  970.             
  971.             unless ($had_breakpoints{$file} &= ~2) {
  972.                 delete $had_breakpoints{$file};
  973.             }
  974.               }
  975.               next CMD; };
  976.             $cmd =~ /^O\s*$/ && do {
  977.             for (@options) {
  978.                 &dump_option($_);
  979.             }
  980.             next CMD; };
  981.             $cmd =~ /^O\s*(\S.*)/ && do {
  982.             parse_options($1);
  983.             next CMD; };
  984.             $cmd =~ /^\<\<\s*(.*)/ && do { # \<\< for CPerl sake: not HERE
  985.             push @$pre, action($1);
  986.             next CMD; };
  987.             $cmd =~ /^>>\s*(.*)/ && do {
  988.             push @$post, action($1);
  989.             next CMD; };
  990.             $cmd =~ /^<\s*(.*)/ && do {
  991.             unless ($1) {
  992.                 print $OUT "All < actions cleared.\n";
  993.                 $pre = [];
  994.                 next CMD;
  995.             } 
  996.             if ($1 eq '?') {
  997.                 unless (@$pre) {
  998.                 print $OUT "No pre-prompt Perl actions.\n";
  999.                 next CMD;
  1000.                 } 
  1001.                 print $OUT "Perl commands run before each prompt:\n";
  1002.                 for my $action ( @$pre ) {
  1003.                 print $OUT "\t< -- $action\n";
  1004.                 } 
  1005.                 next CMD;
  1006.             } 
  1007.             $pre = [action($1)];
  1008.             next CMD; };
  1009.             $cmd =~ /^>\s*(.*)/ && do {
  1010.             unless ($1) {
  1011.                 print $OUT "All > actions cleared.\n";
  1012.                 $post = [];
  1013.                 next CMD;
  1014.             }
  1015.             if ($1 eq '?') {
  1016.                 unless (@$post) {
  1017.                 print $OUT "No post-prompt Perl actions.\n";
  1018.                 next CMD;
  1019.                 } 
  1020.                 print $OUT "Perl commands run after each prompt:\n";
  1021.                 for my $action ( @$post ) {
  1022.                 print $OUT "\t> -- $action\n";
  1023.                 } 
  1024.                 next CMD;
  1025.             } 
  1026.             $post = [action($1)];
  1027.             next CMD; };
  1028.             $cmd =~ /^\{\{\s*(.*)/ && do {
  1029.             if ($cmd =~ /^\{.*\}$/ && unbalanced(substr($cmd,2))) { 
  1030.                 print $OUT "{{ is now a debugger command\n",
  1031.                 "use `;{{' if you mean Perl code\n";
  1032.                 $cmd = "h {{";
  1033.                 redo CMD;
  1034.             } 
  1035.             push @$pretype, $1;
  1036.             next CMD; };
  1037.             $cmd =~ /^\{\s*(.*)/ && do {
  1038.             unless ($1) {
  1039.                 print $OUT "All { actions cleared.\n";
  1040.                 $pretype = [];
  1041.                 next CMD;
  1042.             }
  1043.             if ($1 eq '?') {
  1044.                 unless (@$pretype) {
  1045.                 print $OUT "No pre-prompt debugger actions.\n";
  1046.                 next CMD;
  1047.                 } 
  1048.                 print $OUT "Debugger commands run before each prompt:\n";
  1049.                 for my $action ( @$pretype ) {
  1050.                 print $OUT "\t{ -- $action\n";
  1051.                 } 
  1052.                 next CMD;
  1053.             } 
  1054.             if ($cmd =~ /^\{.*\}$/ && unbalanced(substr($cmd,1))) { 
  1055.                 print $OUT "{ is now a debugger command\n",
  1056.                 "use `;{' if you mean Perl code\n";
  1057.                 $cmd = "h {";
  1058.                 redo CMD;
  1059.             } 
  1060.             $pretype = [$1];
  1061.             next CMD; };
  1062.             $cmd =~ /^a\b\s*(\d*)\s*(.*)/ && do {
  1063.             $i = $1 || $line; $j = $2;
  1064.             if (length $j) {
  1065.                 if ($dbline[$i] == 0) {
  1066.                 print $OUT "Line $i may not have an action.\n";
  1067.                 } else {
  1068.                 $had_breakpoints{$filename} |= 2;
  1069.                 $dbline{$i} =~ s/\0[^\0]*//;
  1070.                 $dbline{$i} .= "\0" . action($j);
  1071.                 }
  1072.             } else {
  1073.                 $dbline{$i} =~ s/\0[^\0]*//;
  1074.                 delete $dbline{$i} if $dbline{$i} eq '';
  1075.             }
  1076.             next CMD; };
  1077.             $cmd =~ /^n$/ && do {
  1078.                 end_report(), next CMD if $finished and $level <= 1;
  1079.             $single = 2;
  1080.             $laststep = $cmd;
  1081.             last CMD; };
  1082.             $cmd =~ /^s$/ && do {
  1083.                 end_report(), next CMD if $finished and $level <= 1;
  1084.             $single = 1;
  1085.             $laststep = $cmd;
  1086.             last CMD; };
  1087.             $cmd =~ /^c\b\s*([\w:]*)\s*$/ && do {
  1088.                 end_report(), next CMD if $finished and $level <= 1;
  1089.             $subname = $i = $1;
  1090.             #  Probably not needed, since we finish an interactive
  1091.             #  sub-session anyway...
  1092.             # local $filename = $filename;
  1093.             # local *dbline = *dbline;    # XXX Would this work?!
  1094.             if ($i =~ /\D/) { # subroutine name
  1095.                 $subname = $package."::".$subname 
  1096.                     unless $subname =~ /::/;
  1097.                 ($file,$i) = (find_sub($subname) =~ /^(.*):(.*)$/);
  1098.                 $i += 0;
  1099.                 if ($i) {
  1100.                     $filename = $file;
  1101.                 *dbline = $main::{'_<' . $filename};
  1102.                 $had_breakpoints{$filename} |= 1;
  1103.                 $max = $#dbline;
  1104.                 ++$i while $dbline[$i] == 0 && $i < $max;
  1105.                 } else {
  1106.                 print $OUT "Subroutine $subname not found.\n";
  1107.                 next CMD; 
  1108.                 }
  1109.             }
  1110.             if ($i) {
  1111.                 if ($dbline[$i] == 0) {
  1112.                 print $OUT "Line $i not breakable.\n";
  1113.                 next CMD;
  1114.                 }
  1115.                 $dbline{$i} =~ s/($|\0)/;9$1/; # add one-time-only b.p.
  1116.             }
  1117.             for ($i=0; $i <= $stack_depth; ) {
  1118.                 $stack[$i++] &= ~1;
  1119.             }
  1120.             last CMD; };
  1121.             $cmd =~ /^r$/ && do {
  1122.                 end_report(), next CMD if $finished and $level <= 1;
  1123.             $stack[$stack_depth] |= 1;
  1124.             $doret = $option{PrintRet} ? $stack_depth - 1 : -2;
  1125.             last CMD; };
  1126.             $cmd =~ /^R$/ && do {
  1127.                 print $OUT "Warning: some settings and command-line options may be lost!\n";
  1128.             my (@script, @flags, $cl);
  1129.             push @flags, '-w' if $ini_warn;
  1130.             # Put all the old includes at the start to get
  1131.             # the same debugger.
  1132.             for (@ini_INC) {
  1133.               push @flags, '-I', $_;
  1134.             }
  1135.             # Arrange for setting the old INC:
  1136.             set_list("PERLDB_INC", @ini_INC);
  1137.             if ($0 eq '-e') {
  1138.               for (1..$#{'::_<-e'}) { # The first line is PERL5DB
  1139.                     chomp ($cl =  ${'::_<-e'}[$_]);
  1140.                 push @script, '-e', $cl;
  1141.               }
  1142.             } else {
  1143.               @script = $0;
  1144.             }
  1145.             set_list("PERLDB_HIST", 
  1146.                  $term->Features->{getHistory} 
  1147.                  ? $term->GetHistory : @hist);
  1148.             my @had_breakpoints = keys %had_breakpoints;
  1149.             set_list("PERLDB_VISITED", @had_breakpoints);
  1150.             set_list("PERLDB_OPT", %option);
  1151.             set_list("PERLDB_ON_LOAD", %break_on_load);
  1152.             my @hard;
  1153.             for (0 .. $#had_breakpoints) {
  1154.               my $file = $had_breakpoints[$_];
  1155.               *dbline = $main::{'_<' . $file};
  1156.               next unless %dbline or $postponed_file{$file};
  1157.               (push @hard, $file), next 
  1158.                 if $file =~ /^\(eval \d+\)$/;
  1159.               my @add;
  1160.               @add = %{$postponed_file{$file}}
  1161.                 if $postponed_file{$file};
  1162.               set_list("PERLDB_FILE_$_", %dbline, @add);
  1163.             }
  1164.             for (@hard) { # Yes, really-really...
  1165.               # Find the subroutines in this eval
  1166.               *dbline = $main::{'_<' . $_};
  1167.               my ($quoted, $sub, %subs, $line) = quotemeta $_;
  1168.               for $sub (keys %sub) {
  1169.                 next unless $sub{$sub} =~ /^$quoted:(\d+)-(\d+)$/;
  1170.                 $subs{$sub} = [$1, $2];
  1171.               }
  1172.               unless (%subs) {
  1173.                 print $OUT
  1174.                   "No subroutines in $_, ignoring breakpoints.\n";
  1175.                 next;
  1176.               }
  1177.             LINES: for $line (keys %dbline) {
  1178.                 # One breakpoint per sub only:
  1179.                 my ($offset, $sub, $found);
  1180.               SUBS: for $sub (keys %subs) {
  1181.                   if ($subs{$sub}->[1] >= $line # Not after the subroutine
  1182.                   and (not defined $offset # Not caught
  1183.                        or $offset < 0 )) { # or badly caught
  1184.                 $found = $sub;
  1185.                 $offset = $line - $subs{$sub}->[0];
  1186.                 $offset = "+$offset", last SUBS if $offset >= 0;
  1187.                   }
  1188.                 }
  1189.                 if (defined $offset) {
  1190.                   $postponed{$found} =
  1191.                 "break $offset if $dbline{$line}";
  1192.                 } else {
  1193.                   print $OUT "Breakpoint in $_:$line ignored: after all the subroutines.\n";
  1194.                 }
  1195.               }
  1196.             }
  1197.             set_list("PERLDB_POSTPONE", %postponed);
  1198.             set_list("PERLDB_PRETYPE", @$pretype);
  1199.             set_list("PERLDB_PRE", @$pre);
  1200.             set_list("PERLDB_POST", @$post);
  1201.             set_list("PERLDB_TYPEAHEAD", @typeahead);
  1202.             $ENV{PERLDB_RESTART} = 1;
  1203.             #print "$^X, '-d', @flags, @script, ($slave_editor ? '-emacs' : ()), @ARGS";
  1204.             exec $^X, '-d', @flags, @script, ($slave_editor ? '-emacs' : ()), @ARGS;
  1205.             print $OUT "exec failed: $!\n";
  1206.             last CMD; };
  1207.             $cmd =~ /^T$/ && do {
  1208.             print_trace($OUT, 1); # skip DB
  1209.             next CMD; };
  1210.             $cmd =~ /^W\s*$/ && do {
  1211.             $trace &= ~2;
  1212.             @to_watch = @old_watch = ();
  1213.             next CMD; };
  1214.             $cmd =~ /^W\b\s*(.*)/s && do {
  1215.             push @to_watch, $1;
  1216.             $evalarg = $1;
  1217.             my ($val) = &eval;
  1218.             $val = (defined $val) ? "'$val'" : 'undef' ;
  1219.             push @old_watch, $val;
  1220.             $trace |= 2;
  1221.             next CMD; };
  1222.             $cmd =~ /^\/(.*)$/ && do {
  1223.             $inpat = $1;
  1224.             $inpat =~ s:([^\\])/$:$1:;
  1225.             if ($inpat ne "") {
  1226.                 # squelch the sigmangler
  1227.                 local $SIG{__DIE__};
  1228.                 local $SIG{__WARN__};
  1229.                 eval '$inpat =~ m'."\a$inpat\a";    
  1230.                 if ($@ ne "") {
  1231.                 print $OUT "$@";
  1232.                 next CMD;
  1233.                 }
  1234.                 $pat = $inpat;
  1235.             }
  1236.             $end = $start;
  1237.             $incr = -1;
  1238.             eval '
  1239.                 for (;;) {
  1240.                 ++$start;
  1241.                 $start = 1 if ($start > $max);
  1242.                 last if ($start == $end);
  1243.                 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
  1244.                     if ($slave_editor) {
  1245.                     print $OUT "\032\032$filename:$start:0\n";
  1246.                     } else {
  1247.                     print $OUT "$start:\t", $dbline[$start], "\n";
  1248.                     }
  1249.                     last;
  1250.                 }
  1251.                 } ';
  1252.             print $OUT "/$pat/: not found\n" if ($start == $end);
  1253.             next CMD; };
  1254.             $cmd =~ /^\?(.*)$/ && do {
  1255.             $inpat = $1;
  1256.             $inpat =~ s:([^\\])\?$:$1:;
  1257.             if ($inpat ne "") {
  1258.                 # squelch the sigmangler
  1259.                 local $SIG{__DIE__};
  1260.                 local $SIG{__WARN__};
  1261.                 eval '$inpat =~ m'."\a$inpat\a";    
  1262.                 if ($@ ne "") {
  1263.                 print $OUT $@;
  1264.                 next CMD;
  1265.                 }
  1266.                 $pat = $inpat;
  1267.             }
  1268.             $end = $start;
  1269.             $incr = -1;
  1270.             eval '
  1271.                 for (;;) {
  1272.                 --$start;
  1273.                 $start = $max if ($start <= 0);
  1274.                 last if ($start == $end);
  1275.                 if ($dbline[$start] =~ m' . "\a$pat\a" . 'i) {
  1276.                     if ($slave_editor) {
  1277.                     print $OUT "\032\032$filename:$start:0\n";
  1278.                     } else {
  1279.                     print $OUT "$start:\t", $dbline[$start], "\n";
  1280.                     }
  1281.                     last;
  1282.                 }
  1283.                 } ';
  1284.             print $OUT "?$pat?: not found\n" if ($start == $end);
  1285.             next CMD; };
  1286.             $cmd =~ /^$rc+\s*(-)?(\d+)?$/ && do {
  1287.             pop(@hist) if length($cmd) > 1;
  1288.             $i = $1 ? ($#hist-($2||1)) : ($2||$#hist);
  1289.             $cmd = $hist[$i];
  1290.             print $OUT $cmd, "\n";
  1291.             redo CMD; };
  1292.             $cmd =~ /^$sh$sh\s*([\x00-\xff]*)/ && do {
  1293.             &system($1);
  1294.             next CMD; };
  1295.             $cmd =~ /^$rc([^$rc].*)$/ && do {
  1296.             $pat = "^$1";
  1297.             pop(@hist) if length($cmd) > 1;
  1298.             for ($i = $#hist; $i; --$i) {
  1299.                 last if $hist[$i] =~ /$pat/;
  1300.             }
  1301.             if (!$i) {
  1302.                 print $OUT "No such command!\n\n";
  1303.                 next CMD;
  1304.             }
  1305.             $cmd = $hist[$i];
  1306.             print $OUT $cmd, "\n";
  1307.             redo CMD; };
  1308.             $cmd =~ /^$sh$/ && do {
  1309.             &system($ENV{SHELL}||"/bin/sh");
  1310.             next CMD; };
  1311.             $cmd =~ /^$sh\s*([\x00-\xff]*)/ && do {
  1312.             # XXX: using csh or tcsh destroys sigint retvals!
  1313.             #&system($1);  # use this instead
  1314.             &system($ENV{SHELL}||"/bin/sh","-c",$1);
  1315.             next CMD; };
  1316.             $cmd =~ /^H\b\s*(-(\d+))?/ && do {
  1317.             $end = $2 ? ($#hist-$2) : 0;
  1318.             $hist = 0 if $hist < 0;
  1319.             for ($i=$#hist; $i>$end; $i--) {
  1320.                 print $OUT "$i: ",$hist[$i],"\n"
  1321.                   unless $hist[$i] =~ /^.?$/;
  1322.             };
  1323.             next CMD; };
  1324.             $cmd =~ /^(?:man|(?:perl)?doc)\b(?:\s+([^(]*))?$/ && do {
  1325.             runman($1);
  1326.             next CMD; };
  1327.             $cmd =~ s/^p$/print {\$DB::OUT} \$_/;
  1328.             $cmd =~ s/^p\b/print {\$DB::OUT} /;
  1329.             $cmd =~ s/^=\s*// && do {
  1330.             my @keys;
  1331.             if (length $cmd == 0) {
  1332.                 @keys = sort keys %alias;
  1333.             } 
  1334.                         elsif (my($k,$v) = ($cmd =~ /^(\S+)\s+(\S.*)/)) {
  1335.                 # can't use $_ or kill //g state
  1336.                 for my $x ($k, $v) { $x =~ s/\a/\\a/g }
  1337.                 $alias{$k} = "s\a$k\a$v\a";
  1338.                 # squelch the sigmangler
  1339.                 local $SIG{__DIE__};
  1340.                 local $SIG{__WARN__};
  1341.                 unless (eval "sub { s\a$k\a$v\a }; 1") {
  1342.                 print $OUT "Can't alias $k to $v: $@\n"; 
  1343.                 delete $alias{$k};
  1344.                 next CMD;
  1345.                 } 
  1346.                 @keys = ($k);
  1347.             } 
  1348.             else {
  1349.                 @keys = ($cmd);
  1350.             } 
  1351.             for my $k (@keys) {
  1352.                 if ((my $v = $alias{$k}) =~ ss\a$k\a(.*)\a$1) {
  1353.                 print $OUT "$k\t= $1\n";
  1354.                 } 
  1355.                 elsif (defined $alias{$k}) {
  1356.                     print $OUT "$k\t$alias{$k}\n";
  1357.                 } 
  1358.                 else {
  1359.                 print "No alias for $k\n";
  1360.                 } 
  1361.             }
  1362.             next CMD; };
  1363.             $cmd =~ /^\|\|?\s*[^|]/ && do {
  1364.             if ($pager =~ /^\|/) {
  1365.                 open(SAVEOUT,">&STDOUT") || &warn("Can't save STDOUT");
  1366.                 open(STDOUT,">&OUT") || &warn("Can't redirect STDOUT");
  1367.             } else {
  1368.                 open(SAVEOUT,">&OUT") || &warn("Can't save DB::OUT");
  1369.             }
  1370.             fix_less();
  1371.             unless ($piped=open(OUT,$pager)) {
  1372.                 &warn("Can't pipe output to `$pager'");
  1373.                 if ($pager =~ /^\|/) {
  1374.                 open(OUT,">&STDOUT") # XXX: lost message
  1375.                     || &warn("Can't restore DB::OUT");
  1376.                 open(STDOUT,">&SAVEOUT")
  1377.                   || &warn("Can't restore STDOUT");
  1378.                 close(SAVEOUT);
  1379.                 } else {
  1380.                 open(OUT,">&STDOUT") # XXX: lost message
  1381.                     || &warn("Can't restore DB::OUT");
  1382.                 }
  1383.                 next CMD;
  1384.             }
  1385.             $SIG{PIPE}= \&DB::catch if $pager =~ /^\|/
  1386.                 && ("" eq $SIG{PIPE}  ||  "DEFAULT" eq $SIG{PIPE});
  1387.             $selected= select(OUT);
  1388.             $|= 1;
  1389.             select( $selected ), $selected= "" unless $cmd =~ /^\|\|/;
  1390.             $cmd =~ s/^\|+\s*//;
  1391.             redo PIPE; 
  1392.             };
  1393.             # XXX Local variants do not work!
  1394.             $cmd =~ s/^t\s/\$DB::trace |= 1;\n/;
  1395.             $cmd =~ s/^s\s/\$DB::single = 1;\n/ && do {$laststep = 's'};
  1396.             $cmd =~ s/^n\s/\$DB::single = 2;\n/ && do {$laststep = 'n'};
  1397.         }        # PIPE:
  1398.         $evalarg = "\$^D = \$^D | \$DB::db_stop;\n$cmd"; &eval;
  1399.         if ($onetimeDump) {
  1400.         $onetimeDump = undef;
  1401.         } elsif ($term_pid == $$) {
  1402.         print $OUT "\n";
  1403.         }
  1404.     } continue {        # CMD:
  1405.         if ($piped) {
  1406.         if ($pager =~ /^\|/) {
  1407.             $? = 0;  
  1408.             # we cannot warn here: the handle is missing --tchrist
  1409.             close(OUT) || print SAVEOUT "\nCan't close DB::OUT\n";
  1410.  
  1411.             # most of the $? crud was coping with broken cshisms
  1412.             if ($?) {
  1413.             print SAVEOUT "Pager `$pager' failed: ";
  1414.             if ($? == -1) {
  1415.                 print SAVEOUT "shell returned -1\n";
  1416.             } elsif ($? >> 8) {
  1417.                 print SAVEOUT 
  1418.                   ( $? & 127 ) ? " (SIG#".($?&127).")" : "", 
  1419.                   ( $? & 128 ) ? " -- core dumped" : "", "\n";
  1420.             } else {
  1421.                 print SAVEOUT "status ", ($? >> 8), "\n";
  1422.             } 
  1423.             } 
  1424.  
  1425.             open(OUT,">&STDOUT") || &warn("Can't restore DB::OUT");
  1426.             open(STDOUT,">&SAVEOUT") || &warn("Can't restore STDOUT");
  1427.             $SIG{PIPE} = "DEFAULT" if $SIG{PIPE} eq \&DB::catch;
  1428.             # Will stop ignoring SIGPIPE if done like nohup(1)
  1429.             # does SIGINT but Perl doesn't give us a choice.
  1430.         } else {
  1431.             open(OUT,">&SAVEOUT") || &warn("Can't restore DB::OUT");
  1432.         }
  1433.         close(SAVEOUT);
  1434.         select($selected), $selected= "" unless $selected eq "";
  1435.         $piped= "";
  1436.         }
  1437.     }            # CMD:
  1438.        $fall_off_end = 1 unless defined $cmd; # Emulate `q' on EOF
  1439.     foreach $evalarg (@$post) {
  1440.       &eval;
  1441.     }
  1442.     }                # if ($single || $signal)
  1443.     ($@, $!, $^E, $,, $/, $\, $^W) = @saved;
  1444.     ();
  1445. }
  1446.  
  1447. # The following code may be executed now:
  1448. # BEGIN {warn 4}
  1449.  
  1450. sub sub {
  1451.     my ($al, $ret, @ret) = "";
  1452.     if (length($sub) > 10 && substr($sub, -10, 10) eq '::AUTOLOAD') {
  1453.     $al = " for $$sub";
  1454.     }
  1455.     local $stack_depth = $stack_depth + 1; # Protect from non-local exits
  1456.     $#stack = $stack_depth;
  1457.     $stack[-1] = $single;
  1458.     $single &= 1;
  1459.     $single |= 4 if $stack_depth == $deep;
  1460.     ($frame & 4 
  1461.      ? ( (print $LINEINFO ' ' x ($stack_depth - 1), "in  "), 
  1462.      # Why -1? But it works! :-(
  1463.      print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
  1464.      : print $LINEINFO ' ' x ($stack_depth - 1), "entering $sub$al\n") if $frame;
  1465.     if (wantarray) {
  1466.     @ret = &$sub;
  1467.     $single |= $stack[$stack_depth--];
  1468.     ($frame & 4 
  1469.      ? ( (print $LINEINFO ' ' x $stack_depth, "out "), 
  1470.          print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
  1471.      : print $LINEINFO ' ' x $stack_depth, "exited $sub$al\n") if $frame & 2;
  1472.     if ($doret eq $stack_depth or $frame & 16) {
  1473.             my $fh = ($doret eq $stack_depth ? $OUT : $LINEINFO);
  1474.         print $fh ' ' x $stack_depth if $frame & 16;
  1475.         print $fh "list context return from $sub:\n"; 
  1476.         dumpit($fh, \@ret );
  1477.         $doret = -2;
  1478.     }
  1479.     @ret;
  1480.     } else {
  1481.         if (defined wantarray) {
  1482.         $ret = &$sub;
  1483.         } else {
  1484.             &$sub; undef $ret;
  1485.         };
  1486.     $single |= $stack[$stack_depth--];
  1487.     ($frame & 4 
  1488.      ? ( (print $LINEINFO ' ' x $stack_depth, "out "), 
  1489.           print_trace($LINEINFO, -1, 1, 1, "$sub$al") )
  1490.      : print $LINEINFO ' ' x $stack_depth, "exited $sub$al\n") if $frame & 2;
  1491.     if ($doret eq $stack_depth or $frame & 16 and defined wantarray) {
  1492.             my $fh = ($doret eq $stack_depth ? $OUT : $LINEINFO);
  1493.         print $fh (' ' x $stack_depth) if $frame & 16;
  1494.         print $fh (defined wantarray 
  1495.              ? "scalar context return from $sub: " 
  1496.              : "void context return from $sub\n");
  1497.         dumpit( $fh, $ret ) if defined wantarray;
  1498.         $doret = -2;
  1499.     }
  1500.     $ret;
  1501.     }
  1502. }
  1503.  
  1504. sub save {
  1505.     @saved = ($@, $!, $^E, $,, $/, $\, $^W);
  1506.     $, = ""; $/ = "\n"; $\ = ""; $^W = 0;
  1507. }
  1508.  
  1509. # The following takes its argument via $evalarg to preserve current @_
  1510.  
  1511. sub eval {
  1512.     # 'my' would make it visible from user code
  1513.     #    but so does local! --tchrist  
  1514.     local @res;            
  1515.     {
  1516.     local $otrace = $trace;
  1517.     local $osingle = $single;
  1518.     local $od = $^D;
  1519.     { ($evalarg) = $evalarg =~ /(.*)/s; }
  1520.     @res = eval "$usercontext $evalarg;\n"; # '\n' for nice recursive debug
  1521.     $trace = $otrace;
  1522.     $single = $osingle;
  1523.     $^D = $od;
  1524.     }
  1525.     my $at = $@;
  1526.     local $saved[0];        # Preserve the old value of $@
  1527.     eval { &DB::save };
  1528.     if ($at) {
  1529.     print $OUT $at;
  1530.     } elsif ($onetimeDump eq 'dump') {
  1531.     dumpit($OUT, \@res);
  1532.     } elsif ($onetimeDump eq 'methods') {
  1533.     methods($res[0]);
  1534.     }
  1535.     @res;
  1536. }
  1537.  
  1538. sub postponed_sub {
  1539.   my $subname = shift;
  1540.   if ($postponed{$subname} =~ s/^break\s([+-]?\d+)\s+if\s//) {
  1541.     my $offset = $1 || 0;
  1542.     # Filename below can contain ':'
  1543.     my ($file,$i) = (find_sub($subname) =~ /^(.*):(\d+)-.*$/);
  1544.     if ($i) {
  1545.       $i += $offset;
  1546.       local *dbline = $main::{'_<' . $file};
  1547.       local $^W = 0;        # != 0 is magical below
  1548.       $had_breakpoints{$file} |= 1;
  1549.       my $max = $#dbline;
  1550.       ++$i until $dbline[$i] != 0 or $i >= $max;
  1551.       $dbline{$i} = delete $postponed{$subname};
  1552.     } else {
  1553.       print $OUT "Subroutine $subname not found.\n";
  1554.     }
  1555.     return;
  1556.   }
  1557.   elsif ($postponed{$subname} eq 'compile') { $signal = 1 }
  1558.   #print $OUT "In postponed_sub for `$subname'.\n";
  1559. }
  1560.  
  1561. sub postponed {
  1562.   if ($ImmediateStop) {
  1563.     $ImmediateStop = 0;
  1564.     $signal = 1;
  1565.   }
  1566.   return &postponed_sub
  1567.     unless ref \$_[0] eq 'GLOB'; # A subroutine is compiled.
  1568.   # Cannot be done before the file is compiled
  1569.   local *dbline = shift;
  1570.   my $filename = $dbline;
  1571.   $filename =~ s/^_<//;
  1572.   $signal = 1, print $OUT "'$filename' loaded...\n"
  1573.     if $break_on_load{$filename};
  1574.   print $LINEINFO ' ' x $stack_depth, "Package $filename.\n" if $frame;
  1575.   return unless $postponed_file{$filename};
  1576.   $had_breakpoints{$filename} |= 1;
  1577.   #%dbline = %{$postponed_file{$filename}}; # Cannot be done: unsufficient magic
  1578.   my $key;
  1579.   for $key (keys %{$postponed_file{$filename}}) {
  1580.     $dbline{$key} = ${$postponed_file{$filename}}{$key};
  1581.   }
  1582.   delete $postponed_file{$filename};
  1583. }
  1584.  
  1585. sub dumpit {
  1586.     local ($savout) = select(shift);
  1587.     my $osingle = $single;
  1588.     my $otrace = $trace;
  1589.     $single = $trace = 0;
  1590.     local $frame = 0;
  1591.     local $doret = -2;
  1592.     unless (defined &main::dumpValue) {
  1593.     do 'dumpvar.pl';
  1594.     }
  1595.     if (defined &main::dumpValue) {
  1596.     &main::dumpValue(shift);
  1597.     } else {
  1598.     print $OUT "dumpvar.pl not available.\n";
  1599.     }
  1600.     $single = $osingle;
  1601.     $trace = $otrace;
  1602.     select ($savout);    
  1603. }
  1604.  
  1605. # Tied method do not create a context, so may get wrong message:
  1606.  
  1607. sub print_trace {
  1608.   my $fh = shift;
  1609.   my @sub = dump_trace($_[0] + 1, $_[1]);
  1610.   my $short = $_[2];        # Print short report, next one for sub name
  1611.   my $s;
  1612.   for ($i=0; $i <= $#sub; $i++) {
  1613.     last if $signal;
  1614.     local $" = ', ';
  1615.     my $args = defined $sub[$i]{args} 
  1616.     ? "(@{ $sub[$i]{args} })"
  1617.       : '' ;
  1618.     $args = (substr $args, 0, $maxtrace - 3) . '...' 
  1619.       if length $args > $maxtrace;
  1620.     my $file = $sub[$i]{file};
  1621.     $file = $file eq '-e' ? $file : "file `$file'" unless $short;
  1622.     $s = $sub[$i]{sub};
  1623.     $s = (substr $s, 0, $maxtrace - 3) . '...' if length $s > $maxtrace;    
  1624.     if ($short) {
  1625.       my $sub = @_ >= 4 ? $_[3] : $s;
  1626.       print $fh "$sub[$i]{context}=$sub$args from $file:$sub[$i]{line}\n";
  1627.     } else {
  1628.       print $fh "$sub[$i]{context} = $s$args" .
  1629.     " called from $file" . 
  1630.       " line $sub[$i]{line}\n";
  1631.     }
  1632.   }
  1633. }
  1634.  
  1635. sub dump_trace {
  1636.   my $skip = shift;
  1637.   my $count = shift || 1e9;
  1638.   $skip++;
  1639.   $count += $skip;
  1640.   my ($p,$file,$line,$sub,$h,$args,$e,$r,@a,@sub,$context);
  1641.   my $nothard = not $frame & 8;
  1642.   local $frame = 0;        # Do not want to trace this.
  1643.   my $otrace = $trace;
  1644.   $trace = 0;
  1645.   for ($i = $skip; 
  1646.        $i < $count and ($p,$file,$line,$sub,$h,$context,$e,$r) = caller($i); 
  1647.        $i++) {
  1648.     @a = ();
  1649.     for $arg (@args) {
  1650.       my $type;
  1651.       if (not defined $arg) {
  1652.     push @a, "undef";
  1653.       } elsif ($nothard and tied $arg) {
  1654.     push @a, "tied";
  1655.       } elsif ($nothard and $type = ref $arg) {
  1656.     push @a, "ref($type)";
  1657.       } else {
  1658.     local $_ = "$arg";    # Safe to stringify now - should not call f().
  1659.     s/([\'\\])/\\$1/g;
  1660.     s/(.*)/'$1'/s
  1661.       unless /^(?: -?[\d.]+ | \*[\w:]* )$/x;
  1662.     s/([\200-\377])/sprintf("M-%c",ord($1)&0177)/eg;
  1663.     s/([\0-\37\177])/sprintf("^%c",ord($1)^64)/eg;
  1664.     push(@a, $_);
  1665.       }
  1666.     }
  1667.     $context = $context ? '@' : (defined $context ? "\$" : '.');
  1668.     $args = $h ? [@a] : undef;
  1669.     $e =~ s/\n\s*\;\s*\Z// if $e;
  1670.     $e =~ s/([\\\'])/\\$1/g if $e;
  1671.     if ($r) {
  1672.       $sub = "require '$e'";
  1673.     } elsif (defined $r) {
  1674.       $sub = "eval '$e'";
  1675.     } elsif ($sub eq '(eval)') {
  1676.       $sub = "eval {...}";
  1677.     }
  1678.     push(@sub, {context => $context, sub => $sub, args => $args,
  1679.         file => $file, line => $line});
  1680.     last if $signal;
  1681.   }
  1682.   $trace = $otrace;
  1683.   @sub;
  1684. }
  1685.  
  1686. sub action {
  1687.     my $action = shift;
  1688.     while ($action =~ s/\\$//) {
  1689.     #print $OUT "+ ";
  1690.     #$action .= "\n";
  1691.     $action .= &gets;
  1692.     }
  1693.     $action;
  1694. }
  1695.  
  1696. sub unbalanced { 
  1697.     # i hate using globals!
  1698.     $balanced_brace_re ||= qr{ 
  1699.     ^ \{
  1700.           (?:
  1701.          (?> [^{}] + )            # Non-parens without backtracking
  1702.            |
  1703.          (??{ $balanced_brace_re }) # Group with matching parens
  1704.           ) *
  1705.       \} $
  1706.    }x;
  1707.    return $_[0] !~ m/$balanced_brace_re/;
  1708. }
  1709.  
  1710. sub gets {
  1711.     &readline("cont: ");
  1712. }
  1713.  
  1714. sub system {
  1715.     # We save, change, then restore STDIN and STDOUT to avoid fork() since
  1716.     # some non-Unix systems can do system() but have problems with fork().
  1717.     open(SAVEIN,"<&STDIN") || &warn("Can't save STDIN");
  1718.     open(SAVEOUT,">&STDOUT") || &warn("Can't save STDOUT");
  1719.     open(STDIN,"<&IN") || &warn("Can't redirect STDIN");
  1720.     open(STDOUT,">&OUT") || &warn("Can't redirect STDOUT");
  1721.  
  1722.     # XXX: using csh or tcsh destroys sigint retvals!
  1723.     system(@_);
  1724.     open(STDIN,"<&SAVEIN") || &warn("Can't restore STDIN");
  1725.     open(STDOUT,">&SAVEOUT") || &warn("Can't restore STDOUT");
  1726.     close(SAVEIN); 
  1727.     close(SAVEOUT);
  1728.  
  1729.  
  1730.     # most of the $? crud was coping with broken cshisms
  1731.     if ($? >> 8) {
  1732.     &warn("(Command exited ", ($? >> 8), ")\n");
  1733.     } elsif ($?) { 
  1734.     &warn( "(Command died of SIG#",  ($? & 127),
  1735.         (($? & 128) ? " -- core dumped" : "") , ")", "\n");
  1736.     } 
  1737.  
  1738.     return $?;
  1739.  
  1740. }
  1741.  
  1742. sub setterm {
  1743.     local $frame = 0;
  1744.     local $doret = -2;
  1745.     eval { require Term::ReadLine } or die $@;
  1746.     if ($notty) {
  1747.     if ($tty) {
  1748.         open(IN,"<$tty") or die "Cannot open TTY `$TTY' for read: $!";
  1749.         open(OUT,">$tty") or die "Cannot open TTY `$TTY' for write: $!";
  1750.         $IN = \*IN;
  1751.         $OUT = \*OUT;
  1752.         my $sel = select($OUT);
  1753.         $| = 1;
  1754.         select($sel);
  1755.     } else {
  1756.         eval "require Term::Rendezvous;" or die;
  1757.         my $rv = $ENV{PERLDB_NOTTY} || "/tmp/perldbtty$$";
  1758.         my $term_rv = new Term::Rendezvous $rv;
  1759.         $IN = $term_rv->IN;
  1760.         $OUT = $term_rv->OUT;
  1761.     }
  1762.     }
  1763.     if (!$rl) {
  1764.     $term = new Term::ReadLine::Stub 'perldb', $IN, $OUT;
  1765.     } else {
  1766.     $term = new Term::ReadLine 'perldb', $IN, $OUT;
  1767.  
  1768.     $rl_attribs = $term->Attribs;
  1769.     $rl_attribs->{basic_word_break_characters} .= '-:+/*,[])}' 
  1770.       if defined $rl_attribs->{basic_word_break_characters} 
  1771.         and index($rl_attribs->{basic_word_break_characters}, ":") == -1;
  1772.     $rl_attribs->{special_prefixes} = '$@&%';
  1773.     $rl_attribs->{completer_word_break_characters} .= '$@&%';
  1774.     $rl_attribs->{completion_function} = \&db_complete; 
  1775.     }
  1776.     $LINEINFO = $OUT unless defined $LINEINFO;
  1777.     $lineinfo = $console unless defined $lineinfo;
  1778.     $term->MinLine(2);
  1779.     if ($term->Features->{setHistory} and "@hist" ne "?") {
  1780.       $term->SetHistory(@hist);
  1781.     }
  1782.     ornaments($ornaments) if defined $ornaments;
  1783.     $term_pid = $$;
  1784. }
  1785.  
  1786. sub resetterm {            # We forked, so we need a different TTY
  1787.     $term_pid = $$;
  1788.     if (defined &get_fork_TTY) {
  1789.       &get_fork_TTY;
  1790.     } elsif (not defined $fork_TTY 
  1791.          and defined $ENV{TERM} and $ENV{TERM} eq 'xterm' 
  1792.          and defined $ENV{WINDOWID} and defined $ENV{DISPLAY}) { 
  1793.         # Possibly _inside_ XTERM
  1794.         open XT, q[3>&1 xterm -title 'Forked Perl debugger' -e sh -c 'tty 1>&3;\
  1795.  sleep 10000000' |];
  1796.         $fork_TTY = <XT>;
  1797.         chomp $fork_TTY;
  1798.     }
  1799.     if (defined $fork_TTY) {
  1800.       TTY($fork_TTY);
  1801.       undef $fork_TTY;
  1802.     } else {
  1803.       print_help(<<EOP);
  1804. I<#########> Forked, but do not know how to change a B<TTY>. I<#########>
  1805.   Define B<\$DB::fork_TTY> 
  1806.        - or a function B<DB::get_fork_TTY()> which will set B<\$DB::fork_TTY>.
  1807.   The value of B<\$DB::fork_TTY> should be the name of I<TTY> to use.
  1808.   On I<UNIX>-like systems one can get the name of a I<TTY> for the given window
  1809.   by typing B<tty>, and disconnect the I<shell> from I<TTY> by B<sleep 1000000>.
  1810. EOP
  1811.     }
  1812. }
  1813.  
  1814. sub readline {
  1815.   local $.;
  1816.   if (@typeahead) {
  1817.     my $left = @typeahead;
  1818.     my $got = shift @typeahead;
  1819.     print $OUT "auto(-$left)", shift, $got, "\n";
  1820.     $term->AddHistory($got) 
  1821.       if length($got) > 1 and defined $term->Features->{addHistory};
  1822.     return $got;
  1823.   }
  1824.   local $frame = 0;
  1825.   local $doret = -2;
  1826.   if (ref $OUT and UNIVERSAL::isa($OUT, 'IO::Socket::INET')) {
  1827.     $OUT->write(join('', @_));
  1828.     my $stuff;
  1829.     $IN->recv( $stuff, 2048 );  # XXX: what's wrong with sysread?
  1830.     $stuff;
  1831.   }
  1832.   else {
  1833.     $term->readline(@_);
  1834.   }
  1835. }
  1836.  
  1837. sub dump_option {
  1838.     my ($opt, $val)= @_;
  1839.     $val = option_val($opt,'N/A');
  1840.     $val =~ s/([\\\'])/\\$1/g;
  1841.     printf $OUT "%20s = '%s'\n", $opt, $val;
  1842. }
  1843.  
  1844. sub option_val {
  1845.     my ($opt, $default)= @_;
  1846.     my $val;
  1847.     if (defined $optionVars{$opt}
  1848.     and defined ${$optionVars{$opt}}) {
  1849.     $val = ${$optionVars{$opt}};
  1850.     } elsif (defined $optionAction{$opt}
  1851.     and defined &{$optionAction{$opt}}) {
  1852.     $val = &{$optionAction{$opt}}();
  1853.     } elsif (defined $optionAction{$opt}
  1854.          and not defined $option{$opt}
  1855.          or defined $optionVars{$opt}
  1856.          and not defined ${$optionVars{$opt}}) {
  1857.     $val = $default;
  1858.     } else {
  1859.     $val = $option{$opt};
  1860.     }
  1861.     $val
  1862. }
  1863.  
  1864. sub parse_options {
  1865.     local($_)= @_;
  1866.     # too dangerous to let intuitive usage overwrite important things
  1867.     # defaultion should never be the default
  1868.     my %opt_needs_val = map { ( $_ => 1 ) } qw{
  1869.         arrayDepth hashDepth LineInfo maxTraceLen ornaments
  1870.         pager quote ReadLine recallCommand RemotePort ShellBang TTY
  1871.     };
  1872.     while (length) {
  1873.     my $val_defaulted;
  1874.     s/^\s+// && next;
  1875.     s/^(\w+)(\W?)// or print($OUT "Invalid option `$_'\n"), last;
  1876.     my ($opt,$sep) = ($1,$2);
  1877.     my $val;
  1878.     if ("?" eq $sep) {
  1879.         print($OUT "Option query `$opt?' followed by non-space `$_'\n"), last
  1880.           if /^\S/;
  1881.         #&dump_option($opt);
  1882.     } elsif ($sep !~ /\S/) {
  1883.         $val_defaulted = 1;
  1884.         $val = "1";  #  this is an evil default; make 'em set it!
  1885.     } elsif ($sep eq "=") {
  1886.  
  1887.             if (s/ (["']) ( (?: \\. | (?! \1 ) [^\\] )* ) \1 //x) { 
  1888.                 my $quote = $1;
  1889.                 ($val = $2) =~ s/\\([$quote\\])/$1/g;
  1890.         } else { 
  1891.         s/^(\S*)//;
  1892.         $val = $1;
  1893.         print OUT qq(Option better cleared using $opt=""\n)
  1894.             unless length $val;
  1895.         }
  1896.  
  1897.     } else { #{ to "let some poor schmuck bounce on the % key in B<vi>."
  1898.         my ($end) = "\\" . substr( ")]>}$sep", index("([<{",$sep), 1 ); #}
  1899.         s/^(([^\\$end]|\\[\\$end])*)$end($|\s+)// or
  1900.           print($OUT "Unclosed option value `$opt$sep$_'\n"), last;
  1901.         ($val = $1) =~ s/\\([\\$end])/$1/g;
  1902.     }
  1903.  
  1904.     my $option;
  1905.     my $matches = grep( /^\Q$opt/  && ($option = $_),  @options  )
  1906.            || grep( /^\Q$opt/i && ($option = $_),  @options  );
  1907.  
  1908.     print($OUT "Unknown option `$opt'\n"), next     unless $matches;
  1909.     print($OUT "Ambiguous option `$opt'\n"), next     if $matches > 1;
  1910.  
  1911.        if ($opt_needs_val{$option} && $val_defaulted) {
  1912.         print $OUT "Option `$opt' is non-boolean.  Use `O $option=VAL' to set, `O $option?' to query\n";
  1913.         next;
  1914.     } 
  1915.  
  1916.     $option{$option} = $val if defined $val;
  1917.  
  1918.     eval qq{
  1919.         local \$frame = 0; 
  1920.         local \$doret = -2; 
  1921.             require '$optionRequire{$option}';
  1922.         1;
  1923.      } || die  # XXX: shouldn't happen
  1924.         if  defined $optionRequire{$option}        &&
  1925.             defined $val;
  1926.  
  1927.     ${$optionVars{$option}} = $val         
  1928.         if  defined $optionVars{$option}        &&
  1929.         defined $val;
  1930.  
  1931.     &{$optionAction{$option}} ($val)    
  1932.         if defined $optionAction{$option}        &&
  1933.                defined &{$optionAction{$option}}    &&
  1934.                defined $val;
  1935.  
  1936.     # Not $rcfile
  1937.     dump_option($option)     unless $OUT eq \*STDERR; 
  1938.     }
  1939. }
  1940.  
  1941. sub set_list {
  1942.   my ($stem,@list) = @_;
  1943.   my $val;
  1944.   $ENV{"${stem}_n"} = @list;
  1945.   for $i (0 .. $#list) {
  1946.     $val = $list[$i];
  1947.     $val =~ s/\\/\\\\/g;
  1948.     $val =~ s/([\0-\37\177\200-\377])/"\\0x" . unpack('H2',$1)/eg;
  1949.     $ENV{"${stem}_$i"} = $val;
  1950.   }
  1951. }
  1952.  
  1953. sub get_list {
  1954.   my $stem = shift;
  1955.   my @list;
  1956.   my $n = delete $ENV{"${stem}_n"};
  1957.   my $val;
  1958.   for $i (0 .. $n - 1) {
  1959.     $val = delete $ENV{"${stem}_$i"};
  1960.     $val =~ s/\\((\\)|0x(..))/ $2 ? $2 : pack('H2', $3) /ge;
  1961.     push @list, $val;
  1962.   }
  1963.   @list;
  1964. }
  1965.  
  1966. sub catch {
  1967.     $signal = 1;
  1968.     return;            # Put nothing on the stack - malloc/free land!
  1969. }
  1970.  
  1971. sub warn {
  1972.     my($msg)= join("",@_);
  1973.     $msg .= ": $!\n" unless $msg =~ /\n$/;
  1974.     print $OUT $msg;
  1975. }
  1976.  
  1977. sub TTY {
  1978.     if (@_ and $term and $term->Features->{newTTY}) {
  1979.       my ($in, $out) = shift;
  1980.       if ($in =~ /,/) {
  1981.     ($in, $out) = split /,/, $in, 2;
  1982.       } else {
  1983.     $out = $in;
  1984.       }
  1985.       open IN, $in or die "cannot open `$in' for read: $!";
  1986.       open OUT, ">$out" or die "cannot open `$out' for write: $!";
  1987.       $term->newTTY(\*IN, \*OUT);
  1988.       $IN    = \*IN;
  1989.       $OUT    = \*OUT;
  1990.       return $tty = $in;
  1991.     } elsif ($term and @_) {
  1992.     &warn("Too late to set TTY, enabled on next `R'!\n");
  1993.     } 
  1994.     $tty = shift if @_;
  1995.     $tty or $console;
  1996. }
  1997.  
  1998. sub noTTY {
  1999.     if ($term) {
  2000.     &warn("Too late to set noTTY, enabled on next `R'!\n") if @_;
  2001.     }
  2002.     $notty = shift if @_;
  2003.     $notty;
  2004. }
  2005.  
  2006. sub ReadLine {
  2007.     if ($term) {
  2008.     &warn("Too late to set ReadLine, enabled on next `R'!\n") if @_;
  2009.     }
  2010.     $rl = shift if @_;
  2011.     $rl;
  2012. }
  2013.  
  2014. sub RemotePort {
  2015.     if ($term) {
  2016.         &warn("Too late to set RemotePort, enabled on next 'R'!\n") if @_;
  2017.     }
  2018.     $remoteport = shift if @_;
  2019.     $remoteport;
  2020. }
  2021.  
  2022. sub tkRunning {
  2023.     if (${$term->Features}{tkRunning}) {
  2024.         return $term->tkRunning(@_);
  2025.     } else {
  2026.     print $OUT "tkRunning not supported by current ReadLine package.\n";
  2027.     0;
  2028.     }
  2029. }
  2030.  
  2031. sub NonStop {
  2032.     if ($term) {
  2033.     &warn("Too late to set up NonStop mode, enabled on next `R'!\n") if @_;
  2034.     }
  2035.     $runnonstop = shift if @_;
  2036.     $runnonstop;
  2037. }
  2038.  
  2039. sub pager {
  2040.     if (@_) {
  2041.     $pager = shift;
  2042.     $pager="|".$pager unless $pager =~ /^(\+?\>|\|)/;
  2043.     }
  2044.     $pager;
  2045. }
  2046.  
  2047. sub shellBang {
  2048.     if (@_) {
  2049.     $sh = quotemeta shift;
  2050.     $sh .= "\\b" if $sh =~ /\w$/;
  2051.     }
  2052.     $psh = $sh;
  2053.     $psh =~ s/\\b$//;
  2054.     $psh =~ s/\\(.)/$1/g;
  2055.     &sethelp;
  2056.     $psh;
  2057. }
  2058.  
  2059. sub ornaments {
  2060.   if (defined $term) {
  2061.     local ($warnLevel,$dieLevel) = (0, 1);
  2062.     return '' unless $term->Features->{ornaments};
  2063.     eval { $term->ornaments(@_) } || '';
  2064.   } else {
  2065.     $ornaments = shift;
  2066.   }
  2067. }
  2068.  
  2069. sub recallCommand {
  2070.     if (@_) {
  2071.     $rc = quotemeta shift;
  2072.     $rc .= "\\b" if $rc =~ /\w$/;
  2073.     }
  2074.     $prc = $rc;
  2075.     $prc =~ s/\\b$//;
  2076.     $prc =~ s/\\(.)/$1/g;
  2077.     &sethelp;
  2078.     $prc;
  2079. }
  2080.  
  2081. sub LineInfo {
  2082.     return $lineinfo unless @_;
  2083.     $lineinfo = shift;
  2084.     my $stream = ($lineinfo =~ /^(\+?\>|\|)/) ? $lineinfo : ">$lineinfo";
  2085.     $slave_editor = ($stream =~ /^\|/);
  2086.     open(LINEINFO, "$stream") || &warn("Cannot open `$stream' for write");
  2087.     $LINEINFO = \*LINEINFO;
  2088.     my $save = select($LINEINFO);
  2089.     $| = 1;
  2090.     select($save);
  2091.     $lineinfo;
  2092. }
  2093.  
  2094. sub list_versions {
  2095.   my %version;
  2096.   my $file;
  2097.   for (keys %INC) {
  2098.     $file = $_;
  2099.     s,\.p[lm]$,,i ;
  2100.     s,/,::,g ;
  2101.     s/^perl5db$/DB/;
  2102.     s/^Term::ReadLine::readline$/readline/;
  2103.     if (defined ${ $_ . '::VERSION' }) {
  2104.       $version{$file} = "${ $_ . '::VERSION' } from ";
  2105.     } 
  2106.     $version{$file} .= $INC{$file};
  2107.   }
  2108.   dumpit($OUT,\%version);
  2109. }
  2110.  
  2111. sub sethelp {
  2112.     # XXX: make sure these are tabs between the command and explantion,
  2113.     #      or print_help will screw up your formatting if you have
  2114.     #      eeevil ornaments enabled.  This is an insane mess.
  2115.  
  2116.     $help = "
  2117. B<T>        Stack trace.
  2118. B<s> [I<expr>]    Single step [in I<expr>].
  2119. B<n> [I<expr>]    Next, steps over subroutine calls [in I<expr>].
  2120. <B<CR>>        Repeat last B<n> or B<s> command.
  2121. B<r>        Return from current subroutine.
  2122. B<c> [I<line>|I<sub>]    Continue; optionally inserts a one-time-only breakpoint
  2123.         at the specified position.
  2124. B<l> I<min>B<+>I<incr>    List I<incr>+1 lines starting at I<min>.
  2125. B<l> I<min>B<->I<max>    List lines I<min> through I<max>.
  2126. B<l> I<line>        List single I<line>.
  2127. B<l> I<subname>    List first window of lines from subroutine.
  2128. B<l> I<\$var>        List first window of lines from subroutine referenced by I<\$var>.
  2129. B<l>        List next window of lines.
  2130. B<->        List previous window of lines.
  2131. B<w> [I<line>]    List window around I<line>.
  2132. B<.>        Return to the executed line.
  2133. B<f> I<filename>    Switch to viewing I<filename>. File must be already loaded.
  2134.         I<filename> may be either the full name of the file, or a regular
  2135.         expression matching the full file name:
  2136.         B<f> I</home/me/foo.pl> and B<f> I<oo\\.> may access the same file.
  2137.         Evals (with saved bodies) are considered to be filenames:
  2138.         B<f> I<(eval 7)> and B<f> I<eval 7\\b> access the body of the 7th eval
  2139.         (in the order of execution).
  2140. B</>I<pattern>B</>    Search forwards for I<pattern>; final B</> is optional.
  2141. B<?>I<pattern>B<?>    Search backwards for I<pattern>; final B<?> is optional.
  2142. B<L>        List all breakpoints and actions.
  2143. B<S> [[B<!>]I<pattern>]    List subroutine names [not] matching I<pattern>.
  2144. B<t>        Toggle trace mode.
  2145. B<t> I<expr>        Trace through execution of I<expr>.
  2146. B<b> [I<line>] [I<condition>]
  2147.         Set breakpoint; I<line> defaults to the current execution line;
  2148.         I<condition> breaks if it evaluates to true, defaults to '1'.
  2149. B<b> I<subname> [I<condition>]
  2150.         Set breakpoint at first line of subroutine.
  2151. B<b> I<\$var>        Set breakpoint at first line of subroutine referenced by I<\$var>.
  2152. B<b> B<load> I<filename> Set breakpoint on `require'ing the given file.
  2153. B<b> B<postpone> I<subname> [I<condition>]
  2154.         Set breakpoint at first line of subroutine after 
  2155.         it is compiled.
  2156. B<b> B<compile> I<subname>
  2157.         Stop after the subroutine is compiled.
  2158. B<d> [I<line>]    Delete the breakpoint for I<line>.
  2159. B<D>        Delete all breakpoints.
  2160. B<a> [I<line>] I<command>
  2161.         Set an action to be done before the I<line> is executed;
  2162.         I<line> defaults to the current execution line.
  2163.         Sequence is: check for breakpoint/watchpoint, print line
  2164.         if necessary, do action, prompt user if necessary,
  2165.         execute line.
  2166. B<a> [I<line>]    Delete the action for I<line>.
  2167. B<A>        Delete all actions.
  2168. B<W> I<expr>        Add a global watch-expression.
  2169. B<W>        Delete all watch-expressions.
  2170. B<V> [I<pkg> [I<vars>]]    List some (default all) variables in package (default current).
  2171.         Use B<~>I<pattern> and B<!>I<pattern> for positive and negative regexps.
  2172. B<X> [I<vars>]    Same as \"B<V> I<currentpackage> [I<vars>]\".
  2173. B<x> I<expr>        Evals expression in list context, dumps the result.
  2174. B<m> I<expr>        Evals expression in list context, prints methods callable
  2175.         on the first element of the result.
  2176. B<m> I<class>        Prints methods callable via the given class.
  2177.  
  2178. B<<> ?            List Perl commands to run before each prompt.
  2179. B<<> I<expr>        Define Perl command to run before each prompt.
  2180. B<<<> I<expr>        Add to the list of Perl commands to run before each prompt.
  2181. B<>> ?            List Perl commands to run after each prompt.
  2182. B<>> I<expr>        Define Perl command to run after each prompt.
  2183. B<>>B<>> I<expr>        Add to the list of Perl commands to run after each prompt.
  2184. B<{> I<db_command>    Define debugger command to run before each prompt.
  2185. B<{> ?            List debugger commands to run before each prompt.
  2186. B<<> I<expr>        Define Perl command to run before each prompt.
  2187. B<{{> I<db_command>    Add to the list of debugger commands to run before each prompt.
  2188. B<$prc> I<number>    Redo a previous command (default previous command).
  2189. B<$prc> I<-number>    Redo number'th-to-last command.
  2190. B<$prc> I<pattern>    Redo last command that started with I<pattern>.
  2191.         See 'B<O> I<recallCommand>' too.
  2192. B<$psh$psh> I<cmd>      Run cmd in a subprocess (reads from DB::IN, writes to DB::OUT)"
  2193.   . ( $rc eq $sh ? "" : "
  2194. B<$psh> [I<cmd>]     Run I<cmd> in subshell (forces \"\$SHELL -c 'cmd'\")." ) . "
  2195.         See 'B<O> I<shellBang>' too.
  2196. B<H> I<-number>    Display last number commands (default all).
  2197. B<p> I<expr>        Same as \"I<print {DB::OUT} expr>\" in current package.
  2198. B<|>I<dbcmd>        Run debugger command, piping DB::OUT to current pager.
  2199. B<||>I<dbcmd>        Same as B<|>I<dbcmd> but DB::OUT is temporarilly select()ed as well.
  2200. B<\=> [I<alias> I<value>]    Define a command alias, or list current aliases.
  2201. I<command>        Execute as a perl statement in current package.
  2202. B<v>        Show versions of loaded modules.
  2203. B<R>        Pure-man-restart of debugger, some of debugger state
  2204.         and command-line options may be lost.
  2205.         Currently the following setting are preserved: 
  2206.         history, breakpoints and actions, debugger B<O>ptions 
  2207.         and the following command-line options: I<-w>, I<-I>, I<-e>.
  2208.  
  2209. B<O> [I<opt>] ...    Set boolean option to true
  2210. B<O> [I<opt>B<?>]    Query options
  2211. B<O> [I<opt>B<=>I<val>] [I<opt>=B<\">I<val>B<\">] ... 
  2212.         Set options.  Use quotes in spaces in value.
  2213.     I<recallCommand>, I<ShellBang>    chars used to recall command or spawn shell;
  2214.     I<pager>            program for output of \"|cmd\";
  2215.     I<tkRunning>            run Tk while prompting (with ReadLine);
  2216.     I<signalLevel> I<warnLevel> I<dieLevel>    level of verbosity;
  2217.     I<inhibit_exit>        Allows stepping off the end of the script.
  2218.     I<ImmediateStop>        Debugger should stop as early as possible.
  2219.     I<RemotePort>            Remote hostname:port for remote debugging
  2220.   The following options affect what happens with B<V>, B<X>, and B<x> commands:
  2221.     I<arrayDepth>, I<hashDepth>     print only first N elements ('' for all);
  2222.     I<compactDump>, I<veryCompact>     change style of array and hash dump;
  2223.     I<globPrint>             whether to print contents of globs;
  2224.     I<DumpDBFiles>         dump arrays holding debugged files;
  2225.     I<DumpPackages>         dump symbol tables of packages;
  2226.     I<DumpReused>             dump contents of \"reused\" addresses;
  2227.     I<quote>, I<HighBit>, I<undefPrint>     change style of string dump;
  2228.     I<bareStringify>         Do not print the overload-stringified value;
  2229.   Other options include:
  2230.     I<PrintRet>        affects printing of return value after B<r> command,
  2231.     I<frame>        affects printing messages on entry and exit from subroutines.
  2232.     I<AutoTrace>    affects printing messages on every possible breaking point.
  2233.     I<maxTraceLen>    gives maximal length of evals/args listed in stack trace.
  2234.     I<ornaments>     affects screen appearance of the command line.
  2235.     During startup options are initialized from \$ENV{PERLDB_OPTS}.
  2236.     You can put additional initialization options I<TTY>, I<noTTY>,
  2237.     I<ReadLine>, I<NonStop>, and I<RemotePort> there (or use
  2238.     `B<R>' after you set them).
  2239.  
  2240. B<q> or B<^D>        Quit. Set B<\$DB::finished = 0> to debug global destruction.
  2241. B<h> [I<db_command>]    Get help [on a specific debugger command], enter B<|h> to page.
  2242. B<h h>        Summary of debugger commands.
  2243. B<$doccmd> I<manpage>    Runs the external doc viewer B<$doccmd> command on the 
  2244.         named Perl I<manpage>, or on B<$doccmd> itself if omitted.
  2245.         Set B<\$DB::doccmd> to change viewer.
  2246.  
  2247. Type `|h' for a paged display if this was too hard to read.
  2248.  
  2249. "; # Fix balance of vi % matching: } }}
  2250.  
  2251.     $summary = <<"END_SUM";
  2252. I<List/search source lines:>               I<Control script execution:>
  2253.   B<l> [I<ln>|I<sub>]  List source code            B<T>           Stack trace
  2254.   B<-> or B<.>      List previous/current line  B<s> [I<expr>]    Single step [in expr]
  2255.   B<w> [I<line>]    List around line            B<n> [I<expr>]    Next, steps over subs
  2256.   B<f> I<filename>  View source in file         <B<CR>/B<Enter>>  Repeat last B<n> or B<s>
  2257.   B</>I<pattern>B</> B<?>I<patt>B<?>   Search forw/backw    B<r>           Return from subroutine
  2258.   B<v>          Show versions of modules    B<c> [I<ln>|I<sub>]  Continue until position
  2259. I<Debugger controls:>                        B<L>           List break/watch/actions
  2260.   B<O> [...]     Set debugger options        B<t> [I<expr>]    Toggle trace [trace expr]
  2261.   B<<>[B<<>]|B<{>[B<{>]|B<>>[B<>>] [I<cmd>] Do pre/post-prompt B<b> [I<ln>|I<event>|I<sub>] [I<cnd>] Set breakpoint
  2262.   B<$prc> [I<N>|I<pat>]   Redo a previous command     B<d> [I<ln>] or B<D> Delete a/all breakpoints
  2263.   B<H> [I<-num>]    Display last num commands   B<a> [I<ln>] I<cmd>  Do cmd before line
  2264.   B<=> [I<a> I<val>]   Define/list an alias        B<W> I<expr>      Add a watch expression
  2265.   B<h> [I<db_cmd>]  Get help on command         B<A> or B<W>      Delete all actions/watch
  2266.   B<|>[B<|>]I<db_cmd>  Send output to pager        B<$psh>\[B<$psh>\] I<syscmd> Run cmd in a subprocess
  2267.   B<q> or B<^D>     Quit              B<R>          Attempt a restart
  2268. I<Data Examination:>          B<expr>     Execute perl code, also see: B<s>,B<n>,B<t> I<expr>
  2269.   B<x>|B<m> I<expr>    Evals expr in list context, dumps the result or lists methods.
  2270.   B<p> I<expr>    Print expression (uses script's current package).
  2271.   B<S> [[B<!>]I<pat>]    List subroutine names [not] matching pattern
  2272.   B<V> [I<Pk> [I<Vars>]]    List Variables in Package.  Vars can be ~pattern or !pattern.
  2273.   B<X> [I<Vars>]    Same as \"B<V> I<current_package> [I<Vars>]\".
  2274. For more help, type B<h> I<cmd_letter>, or run B<$doccmd perldebug> for all docs.
  2275. END_SUM
  2276.                 # ')}}; # Fix balance of vi % matching
  2277. }
  2278.  
  2279. sub print_help {
  2280.     local $_ = shift;
  2281.  
  2282.     # Restore proper alignment destroyed by eeevil I<> and B<>
  2283.     # ornaments: A pox on both their houses!
  2284.     #
  2285.     # A help command will have everything up to and including
  2286.     # the first tab sequence paddeed into a field 16 (or if indented 20)
  2287.     # wide.  If it's wide than that, an extra space will be added.
  2288.     s{
  2289.     ^                 # only matters at start of line
  2290.       ( \040{4} | \t )*    # some subcommands are indented
  2291.       ( < ?         # so <CR> works
  2292.         [BI] < [^\t\n] + )  # find an eeevil ornament
  2293.       ( \t+ )        # original separation, discarded
  2294.       ( .* )        # this will now start (no earlier) than 
  2295.                 # column 16
  2296.     } {
  2297.     my($leadwhite, $command, $midwhite, $text) = ($1, $2, $3, $4);
  2298.     my $clean = $command;
  2299.     $clean =~ s/[BI]<([^>]*)>/$1/g;  
  2300.     # replace with this whole string:
  2301.     (length($leadwhite) ? " " x 4 : "")
  2302.       . $command
  2303.       . ((" " x (16 + (length($leadwhite) ? 4 : 0) - length($clean))) || " ")
  2304.       . $text;
  2305.  
  2306.     }mgex;
  2307.  
  2308.     s{                # handle bold ornaments
  2309.     B < ( [^>] + | > ) >
  2310.     } {
  2311.       $Term::ReadLine::TermCap::rl_term_set[2] 
  2312.     . $1
  2313.     . $Term::ReadLine::TermCap::rl_term_set[3]
  2314.     }gex;
  2315.  
  2316.     s{                # handle italic ornaments
  2317.     I < ( [^>] + | > ) >
  2318.     } {
  2319.       $Term::ReadLine::TermCap::rl_term_set[0] 
  2320.     . $1
  2321.     . $Term::ReadLine::TermCap::rl_term_set[1]
  2322.     }gex;
  2323.  
  2324.     print $OUT $_;
  2325. }
  2326.  
  2327. sub fix_less {
  2328.     return if defined $ENV{LESS} && $ENV{LESS} =~ /r/;
  2329.     my $is_less = $pager =~ /\bless\b/;
  2330.     if ($pager =~ /\bmore\b/) { 
  2331.     my @st_more = stat('/usr/bin/more');
  2332.     my @st_less = stat('/usr/bin/less');
  2333.     $is_less = @st_more    && @st_less 
  2334.         && $st_more[0] == $st_less[0] 
  2335.         && $st_more[1] == $st_less[1];
  2336.     }
  2337.     # changes environment!
  2338.     $ENV{LESS} .= 'r'     if $is_less;
  2339. }
  2340.  
  2341. sub diesignal {
  2342.     local $frame = 0;
  2343.     local $doret = -2;
  2344.     $SIG{'ABRT'} = 'DEFAULT';
  2345.     kill 'ABRT', $$ if $panic++;
  2346.     if (defined &Carp::longmess) {
  2347.     local $SIG{__WARN__} = '';
  2348.     local $Carp::CarpLevel = 2;        # mydie + confess
  2349.     &warn(Carp::longmess("Signal @_"));
  2350.     }
  2351.     else {
  2352.     print $DB::OUT "Got signal @_\n";
  2353.     }
  2354.     kill 'ABRT', $$;
  2355. }
  2356.  
  2357. sub dbwarn { 
  2358.   local $frame = 0;
  2359.   local $doret = -2;
  2360.   local $SIG{__WARN__} = '';
  2361.   local $SIG{__DIE__} = '';
  2362.   eval { require Carp } if defined $^S;    # If error/warning during compilation,
  2363.                                         # require may be broken.
  2364.   warn(@_, "\nCannot print stack trace, load with -MCarp option to see stack"),
  2365.     return unless defined &Carp::longmess;
  2366.   my ($mysingle,$mytrace) = ($single,$trace);
  2367.   $single = 0; $trace = 0;
  2368.   my $mess = Carp::longmess(@_);
  2369.   ($single,$trace) = ($mysingle,$mytrace);
  2370.   &warn($mess); 
  2371. }
  2372.  
  2373. sub dbdie {
  2374.   local $frame = 0;
  2375.   local $doret = -2;
  2376.   local $SIG{__DIE__} = '';
  2377.   local $SIG{__WARN__} = '';
  2378.   my $i = 0; my $ineval = 0; my $sub;
  2379.   if ($dieLevel > 2) {
  2380.       local $SIG{__WARN__} = \&dbwarn;
  2381.       &warn(@_);        # Yell no matter what
  2382.       return;
  2383.   }
  2384.   if ($dieLevel < 2) {
  2385.     die @_ if $^S;        # in eval propagate
  2386.   }
  2387.   eval { require Carp } if defined $^S;    # If error/warning during compilation,
  2388.                                     # require may be broken.
  2389.  
  2390.   die(@_, "\nCannot print stack trace, load with -MCarp option to see stack")
  2391.     unless defined &Carp::longmess;
  2392.  
  2393.   # We do not want to debug this chunk (automatic disabling works
  2394.   # inside DB::DB, but not in Carp).
  2395.   my ($mysingle,$mytrace) = ($single,$trace);
  2396.   $single = 0; $trace = 0;
  2397.   my $mess = Carp::longmess(@_);
  2398.   ($single,$trace) = ($mysingle,$mytrace);
  2399.   die $mess;
  2400. }
  2401.  
  2402. sub warnLevel {
  2403.   if (@_) {
  2404.     $prevwarn = $SIG{__WARN__} unless $warnLevel;
  2405.     $warnLevel = shift;
  2406.     if ($warnLevel) {
  2407.       $SIG{__WARN__} = \&DB::dbwarn;
  2408.     } else {
  2409.       $SIG{__WARN__} = $prevwarn;
  2410.     }
  2411.   }
  2412.   $warnLevel;
  2413. }
  2414.  
  2415. sub dieLevel {
  2416.   if (@_) {
  2417.     $prevdie = $SIG{__DIE__} unless $dieLevel;
  2418.     $dieLevel = shift;
  2419.     if ($dieLevel) {
  2420.       $SIG{__DIE__} = \&DB::dbdie; # if $dieLevel < 2;
  2421.       #$SIG{__DIE__} = \&DB::diehard if $dieLevel >= 2;
  2422.       print $OUT "Stack dump during die enabled", 
  2423.         ( $dieLevel == 1 ? " outside of evals" : ""), ".\n"
  2424.       if $I_m_init;
  2425.       print $OUT "Dump printed too.\n" if $dieLevel > 2;
  2426.     } else {
  2427.       $SIG{__DIE__} = $prevdie;
  2428.       print $OUT "Default die handler restored.\n";
  2429.     }
  2430.   }
  2431.   $dieLevel;
  2432. }
  2433.  
  2434. sub signalLevel {
  2435.   if (@_) {
  2436.     $prevsegv = $SIG{SEGV} unless $signalLevel;
  2437.     $prevbus = $SIG{BUS} unless $signalLevel;
  2438.     $signalLevel = shift;
  2439.     if ($signalLevel) {
  2440.       $SIG{SEGV} = \&DB::diesignal;
  2441.       $SIG{BUS} = \&DB::diesignal;
  2442.     } else {
  2443.       $SIG{SEGV} = $prevsegv;
  2444.       $SIG{BUS} = $prevbus;
  2445.     }
  2446.   }
  2447.   $signalLevel;
  2448. }
  2449.  
  2450. sub CvGV_name {
  2451.   my $in = shift;
  2452.   my $name = CvGV_name_or_bust($in);
  2453.   defined $name ? $name : $in;
  2454. }
  2455.  
  2456. sub CvGV_name_or_bust {
  2457.   my $in = shift;
  2458.   return if $skipCvGV;        # Backdoor to avoid problems if XS broken...
  2459.   $in = \&$in;            # Hard reference...
  2460.   eval {require Devel::Peek; 1} or return;
  2461.   my $gv = Devel::Peek::CvGV($in) or return;
  2462.   *$gv{PACKAGE} . '::' . *$gv{NAME};
  2463. }
  2464.  
  2465. sub find_sub {
  2466.   my $subr = shift;
  2467.   $sub{$subr} or do {
  2468.     return unless defined &$subr;
  2469.     my $name = CvGV_name_or_bust($subr);
  2470.     my $data;
  2471.     $data = $sub{$name} if defined $name;
  2472.     return $data if defined $data;
  2473.  
  2474.     # Old stupid way...
  2475.     $subr = \&$subr;        # Hard reference
  2476.     my $s;
  2477.     for (keys %sub) {
  2478.       $s = $_, last if $subr eq \&$_;
  2479.     }
  2480.     $sub{$s} if $s;
  2481.   }
  2482. }
  2483.  
  2484. sub methods {
  2485.   my $class = shift;
  2486.   $class = ref $class if ref $class;
  2487.   local %seen;
  2488.   local %packs;
  2489.   methods_via($class, '', 1);
  2490.   methods_via('UNIVERSAL', 'UNIVERSAL', 0);
  2491. }
  2492.  
  2493. sub methods_via {
  2494.   my $class = shift;
  2495.   return if $packs{$class}++;
  2496.   my $prefix = shift;
  2497.   my $prepend = $prefix ? "via $prefix: " : '';
  2498.   my $name;
  2499.   for $name (grep {defined &{${"${class}::"}{$_}}} 
  2500.          sort keys %{"${class}::"}) {
  2501.     next if $seen{ $name }++;
  2502.     print $DB::OUT "$prepend$name\n";
  2503.   }
  2504.   return unless shift;        # Recurse?
  2505.   for $name (@{"${class}::ISA"}) {
  2506.     $prepend = $prefix ? $prefix . " -> $name" : $name;
  2507.     methods_via($name, $prepend, 1);
  2508.   }
  2509. }
  2510.  
  2511. sub setman { 
  2512.     $doccmd = $^O !~ /^(?:MSWin32|VMS|os2|dos|amigaos|riscos|MacOS)\z/s
  2513.         ? "man"             # O Happy Day!
  2514.         : "perldoc";        # Alas, poor unfortunates
  2515. }
  2516.  
  2517. sub runman {
  2518.     my $page = shift;
  2519.     unless ($page) {
  2520.     &system("$doccmd $doccmd");
  2521.     return;
  2522.     } 
  2523.     # this way user can override, like with $doccmd="man -Mwhatever"
  2524.     # or even just "man " to disable the path check.
  2525.     unless ($doccmd eq 'man') {
  2526.     &system("$doccmd $page");
  2527.     return;
  2528.     } 
  2529.  
  2530.     $page = 'perl' if lc($page) eq 'help';
  2531.  
  2532.     require Config;
  2533.     my $man1dir = $Config::Config{'man1dir'};
  2534.     my $man3dir = $Config::Config{'man3dir'};
  2535.     for ($man1dir, $man3dir) { s#/[^/]*\z## if /\S/ } 
  2536.     my $manpath = '';
  2537.     $manpath .= "$man1dir:" if $man1dir =~ /\S/;
  2538.     $manpath .= "$man3dir:" if $man3dir =~ /\S/ && $man1dir ne $man3dir;
  2539.     chop $manpath if $manpath;
  2540.     # harmless if missing, I figure
  2541.     my $oldpath = $ENV{MANPATH};
  2542.     $ENV{MANPATH} = $manpath if $manpath;
  2543.     my $nopathopt = $^O =~ /dunno what goes here/;
  2544.     if (system($doccmd, 
  2545.         # I just *know* there are men without -M
  2546.         (($manpath && !$nopathopt) ? ("-M", $manpath) : ()),  
  2547.         split ' ', $page) )
  2548.     {
  2549.     unless ($page =~ /^perl\w/) {
  2550.         if (grep { $page eq $_ } qw{ 
  2551.         5004delta 5005delta amiga api apio book boot bot call compile
  2552.         cygwin data dbmfilter debug debguts delta diag doc dos dsc embed
  2553.         faq faq1 faq2 faq3 faq4 faq5 faq6 faq7 faq8 faq9 filter fork
  2554.         form func guts hack hist hpux intern ipc lexwarn locale lol mod
  2555.         modinstall modlib number obj op opentut os2 os390 pod port 
  2556.         ref reftut run sec style sub syn thrtut tie toc todo toot tootc
  2557.         trap unicode var vms win32 xs xstut
  2558.           }) 
  2559.         {
  2560.         $page =~ s/^/perl/;
  2561.         system($doccmd, 
  2562.             (($manpath && !$nopathopt) ? ("-M", $manpath) : ()),  
  2563.             $page);
  2564.         }
  2565.     }
  2566.     } 
  2567.     if (defined $oldpath) {
  2568.     $ENV{MANPATH} = $manpath;
  2569.     } else {
  2570.     delete $ENV{MANPATH};
  2571.     } 
  2572.  
  2573. # The following BEGIN is very handy if debugger goes havoc, debugging debugger?
  2574.  
  2575. BEGIN {            # This does not compile, alas.
  2576.   $IN = \*STDIN;        # For bugs before DB::OUT has been opened
  2577.   $OUT = \*STDERR;        # For errors before DB::OUT has been opened
  2578.   $sh = '!';
  2579.   $rc = ',';
  2580.   @hist = ('?');
  2581.   $deep = 100;            # warning if stack gets this deep
  2582.   $window = 10;
  2583.   $preview = 3;
  2584.   $sub = '';
  2585.   $SIG{INT} = \&DB::catch;
  2586.   # This may be enabled to debug debugger:
  2587.   #$warnLevel = 1 unless defined $warnLevel;
  2588.   #$dieLevel = 1 unless defined $dieLevel;
  2589.   #$signalLevel = 1 unless defined $signalLevel;
  2590.  
  2591.   $db_stop = 0;            # Compiler warning
  2592.   $db_stop = 1 << 30;
  2593.   $level = 0;            # Level of recursive debugging
  2594.   # @stack and $doret are needed in sub sub, which is called for DB::postponed.
  2595.   # Triggers bug (?) in perl is we postpone this until runtime:
  2596.   @postponed = @stack = (0);
  2597.   $stack_depth = 0;        # Localized $#stack
  2598.   $doret = -2;
  2599.   $frame = 0;
  2600. }
  2601.  
  2602. BEGIN {$^W = $ini_warn;}    # Switch warnings back
  2603.  
  2604. #use Carp;            # This did break, left for debuggin
  2605.  
  2606. sub db_complete {
  2607.   # Specific code for b c l V m f O, &blah, $blah, @blah, %blah
  2608.   my($text, $line, $start) = @_;
  2609.   my ($itext, $search, $prefix, $pack) =
  2610.     ($text, "^\Q${'package'}::\E([^:]+)\$");
  2611.   
  2612.   return sort grep /^\Q$text/, (keys %sub), qw(postpone load compile), # subroutines
  2613.                                (map { /$search/ ? ($1) : () } keys %sub)
  2614.     if (substr $line, 0, $start) =~ /^\|*[blc]\s+((postpone|compile)\s+)?$/;
  2615.   return sort grep /^\Q$text/, values %INC # files
  2616.     if (substr $line, 0, $start) =~ /^\|*b\s+load\s+$/;
  2617.   return sort map {($_, db_complete($_ . "::", "V ", 2))}
  2618.     grep /^\Q$text/, map { /^(.*)::$/ ? ($1) : ()} keys %:: # top-packages
  2619.       if (substr $line, 0, $start) =~ /^\|*[Vm]\s+$/ and $text =~ /^\w*$/;
  2620.   return sort map {($_, db_complete($_ . "::", "V ", 2))}
  2621.     grep !/^main::/,
  2622.       grep /^\Q$text/, map { /^(.*)::$/ ? ($prefix . "::$1") : ()} keys %{$prefix . '::'}
  2623.                  # packages
  2624.     if (substr $line, 0, $start) =~ /^\|*[Vm]\s+$/ 
  2625.       and $text =~ /^(.*[^:])::?(\w*)$/  and $prefix = $1;
  2626.   if ( $line =~ /^\|*f\s+(.*)/ ) { # Loaded files
  2627.     # We may want to complete to (eval 9), so $text may be wrong
  2628.     $prefix = length($1) - length($text);
  2629.     $text = $1;
  2630.     return sort 
  2631.     map {substr $_, 2 + $prefix} grep /^_<\Q$text/, (keys %main::), $0
  2632.   }
  2633.   if ((substr $text, 0, 1) eq '&') { # subroutines
  2634.     $text = substr $text, 1;
  2635.     $prefix = "&";
  2636.     return sort map "$prefix$_", 
  2637.                grep /^\Q$text/, 
  2638.                  (keys %sub),
  2639.                  (map { /$search/ ? ($1) : () } 
  2640.             keys %sub);
  2641.   }
  2642.   if ($text =~ /^[\$@%](.*)::(.*)/) { # symbols in a package
  2643.     $pack = ($1 eq 'main' ? '' : $1) . '::';
  2644.     $prefix = (substr $text, 0, 1) . $1 . '::';
  2645.     $text = $2;
  2646.     my @out 
  2647.       = map "$prefix$_", grep /^\Q$text/, grep /^_?[a-zA-Z]/, keys %$pack ;
  2648.     if (@out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext) {
  2649.       return db_complete($out[0], $line, $start);
  2650.     }
  2651.     return sort @out;
  2652.   }
  2653.   if ($text =~ /^[\$@%]/) { # symbols (in $package + packages in main)
  2654.     $pack = ($package eq 'main' ? '' : $package) . '::';
  2655.     $prefix = substr $text, 0, 1;
  2656.     $text = substr $text, 1;
  2657.     my @out = map "$prefix$_", grep /^\Q$text/, 
  2658.        (grep /^_?[a-zA-Z]/, keys %$pack), 
  2659.        ( $pack eq '::' ? () : (grep /::$/, keys %::) ) ;
  2660.     if (@out == 1 and $out[0] =~ /::$/ and $out[0] ne $itext) {
  2661.       return db_complete($out[0], $line, $start);
  2662.     }
  2663.     return sort @out;
  2664.   }
  2665.   if ((substr $line, 0, $start) =~ /^\|*O\b.*\s$/) { # Options after a space
  2666.     my @out = grep /^\Q$text/, @options;
  2667.     my $val = option_val($out[0], undef);
  2668.     my $out = '? ';
  2669.     if (not defined $val or $val =~ /[\n\r]/) {
  2670.       # Can do nothing better
  2671.     } elsif ($val =~ /\s/) {
  2672.       my $found;
  2673.       foreach $l (split //, qq/\"\'\#\|/) {
  2674.     $out = "$l$val$l ", last if (index $val, $l) == -1;
  2675.       }
  2676.     } else {
  2677.       $out = "=$val ";
  2678.     }
  2679.     # Default to value if one completion, to question if many
  2680.     $rl_attribs->{completer_terminator_character} = (@out == 1 ? $out : '? ');
  2681.     return sort @out;
  2682.   }
  2683.   return $term->filename_list($text); # filenames
  2684. }
  2685.  
  2686. sub end_report {
  2687.   print $OUT "Use `q' to quit or `R' to restart.  `h q' for details.\n"
  2688. }
  2689.  
  2690. END {
  2691.   $finished = 1 if $inhibit_exit;      # So that some keys may be disabled.
  2692.   $fall_off_end = 1 unless $inhibit_exit;
  2693.   # Do not stop in at_exit() and destructors on exit:
  2694.   $DB::single = !$fall_off_end && !$runnonstop;
  2695.   DB::fake::at_exit() unless $fall_off_end or $runnonstop;
  2696. }
  2697.  
  2698. package DB::fake;
  2699.  
  2700. sub at_exit {
  2701.   "Debugged program terminated.  Use `q' to quit or `R' to restart.";
  2702. }
  2703.  
  2704. package DB;            # Do not trace this 1; below!
  2705.  
  2706. 1;
  2707.